└── shell scripting - psa notes.txt /shell scripting - psa notes.txt: -------------------------------------------------------------------------------- 1 | Definition: 2 | ####################################################################################### 3 | Scripting refers to writing a set of commands in a file to be executed sequentially. 4 | 5 | It is used to automate repetitive tasks and system operations. 6 | ------------------------------------------------------------------------------------- 7 | 8 | Why Use Scripting? 9 | ################################################################################# 10 | 1. Reduces manual effort by automating routine tasks. 11 | 12 | 2. Ensures consistency and accuracy in execution. 13 | 14 | 3. Saves time by executing multiple commands at once. 15 | 16 | Example: Automating Daily Commands 17 | -------------------------------------------------------------------------------------- 18 | 19 | Instead of running these commands manually every day: 20 | 21 | whoami 22 | pwd 23 | date 24 | cal 25 | ls -l 26 | 27 | We can store them in a script file (tasks.sh) and execute it: 28 | 29 | $ bash tasks.sh 30 | ---------------------------------------------------------------------------------------- 31 | 32 | What is Shell Scripting? 33 | ################################################################################### 34 | 35 | 1. The process of executing a script file using a shell (command-line interpreter). 36 | 37 | 2. Shell scripting helps automate tasks in projects. 38 | ---------------------------------------------------------------------------------- 39 | 40 | Common Use Cases of Shell Scripting: 41 | ################################################################################### 42 | 43 | -> Backup Automation - Automatically backing up files and databases. 44 | 45 | -> Cleanup Scripts - Removing temporary or unnecessary files. 46 | 47 | -> Log Analysis - Parsing and analyzing system logs. 48 | 49 | -> System Health Checks - Monitoring CPU, memory, and disk usage. 50 | 51 | -> Shell scripts typically have a .sh extension. 52 | -------------------------------------------------------------------------------------- 53 | Examples: 54 | 55 | task.sh # Script to take backup 56 | 57 | Running a Shell Script 58 | 59 | To execute a script, use one of the following commands: 60 | 61 | $ bash task.sh # Execute using Bash 62 | $ ./task.sh # Execute directly (if executable permission is set) 63 | 64 | To make the script executable: 65 | 66 | $ chmod +x task.sh 67 | ---------------------------------------------------------------------------------------- 68 | Shell scripting is a powerful way to automate tasks 69 | 70 | What is Sha-Bang in Linux? 71 | ##################################################################################### 72 | 73 | Definition: 74 | 75 | Sha-Bang (#!) is used to specify which shell should be used to process a script file. It is placed at the beginning of the script file. 76 | 77 | Syntax: 78 | 79 | #! /bin/bash 80 | 81 | #! is called Sha-Bang or Shebang. 82 | 83 | /bin/bash specifies that the script should be executed using the Bash shell. 84 | 85 | Why Use Sha-Bang? 86 | 87 | -> Ensures the script runs in the correct shell regardless of the user's default shell. 88 | 89 | -> Prevents compatibility issues when running scripts across different environments. 90 | ---------------------------------------------------------------------------------------- 91 | 92 | Is Sha-Bang Mandatory? 93 | ######################################################################################## 94 | 95 | -> No, but it is recommended. 96 | 97 | -> If omitted, the script will be executed using the default shell set in the system. 98 | 99 | -> To explicitly define the shell, always include a Sha-Bang line. 100 | 101 | Example Script with Sha-Bang: 102 | ________________________________________________________________________________________ 103 | 104 | #!/bin/bash 105 | 106 | # Print current user 107 | whoami 108 | 109 | # Print current directory 110 | pwd 111 | 112 | # Print date 113 | date 114 | 115 | ------------------------------------------------------------------------------------------ 116 | Alternative to sha-bang 117 | 118 | Sh (Bourne Shell): #!/bin/sh 119 | 120 | Zsh: #!/bin/zsh 121 | ------------------------------------------------------------------------------------------- 122 | 123 | Variable Naming Conventions in Shell 124 | ############################################################################################ 125 | 126 | General Rules for Naming Variables: 127 | -------------------------------------- 128 | 1. Use only letters, numbers, and underscores (_). 129 | 130 | 2. Variable names must start with a letter or underscore (_), not a number. 131 | 132 | 3. Do not use spaces in variable names. 133 | 134 | 4. Avoid special characters (@, #, !, -, etc.). 135 | 136 | 5. Variable names are case-sensitive. 137 | 138 | 139 | Examples of valid convention: 140 | 141 | valid_name="John" 142 | _valid_name="Doe" 143 | VALID_AGE=25 144 | ------------------------------------------ 145 | 146 | Invalid examples: 147 | 148 | 123name="Invalid" # Cannot start with a number 149 | name-with-dash="Bad" # Cannot contain special characters 150 | name space="Wrong" # Cannot contain spaces 151 | 152 | ---------------------------------------------- 153 | 154 | Best Practices: 155 | -------------- 156 | 157 | Use UPPERCASE for constants: 158 | ----------------------------- 159 | MAX_RETRIES=5 160 | ----------------------------- 161 | 162 | -------------------------------------------------- 163 | Use lowercase with underscores for normal variables: 164 | 165 | user_name="Alice" 166 | file_path="/home/alice/documents" 167 | -------------------------------------------------- 168 | 169 | Use meaningful names instead of generic ones: 170 | 171 | counter=10 # Bad 172 | file_count=10 # Good 173 | --------------------------------------------------- 174 | Use double quotes when assigning strings that contain spaces: 175 | 176 | full_name="John Doe" 177 | --------------------------------------------------- 178 | Accessing Variables: 179 | 180 | To retrieve a variable's value, use $: 181 | 182 | name="Alice" 183 | echo "Hello, $name!" 184 | --------------------------------------------------- 185 | 186 | Declaring Read-Only Variables: 187 | 188 | Use readonly to make a variable immutable: 189 | 190 | readonly MY_CONSTANT=100 191 | MY_CONSTANT=200 # Error: cannot modify a readonly variable 192 | ---------------------------------------------------- 193 | 194 | Unsetting a Variable: 195 | 196 | Use unset to remove a variable: 197 | 198 | my_var="Hello" 199 | unset my_var 200 | echo $my_var # No output, variable is deleted 201 | 202 | Following these naming conventions ensures readability, maintainability, and prevents conflicts in shell scripting 203 | --------------------------------------------------- 204 | Example 1: 205 | 206 | #!/bin/bash 207 | 208 | # Prompt the user to enter their name 209 | echo "Enter your name:" 210 | 211 | # Read user input and store it in the variable NAME 212 | read name 213 | 214 | # Greet the user with a customized message 215 | echo "hello, $name" 216 | 217 | Explanation: 218 | 219 | #!/bin/bash 220 | This is called a "shebang" (#!). It tells the system that this script should be executed using the Bash shell. 221 | 222 | echo "Please enter your name:" -Displays a message asking the user to input their name. 223 | 224 | read name - Reads the user’s input from the terminal and stores it in the variable NAME. 225 | 226 | echo "hello, $name" -Prints a greeting message that includes the user's name. 227 | ---------------------------------------------------- 228 | 229 | Example 2: 230 | 231 | #!/bin/bash 232 | 233 | # Prompt the user to enter their first name and store it in the variable FNAME 234 | read -p "Enter your first name: " first_name 235 | 236 | # Prompt the user to enter their last name and store it in the variable LNAME 237 | read -p "Enter your last name: " last_name 238 | 239 | # Display the full name 240 | echo "Hello, $first_name $last_name! Welcome!" 241 | 242 | ------------------------------------------------------------ 243 | 244 | Types of Variables in Linux 245 | In Linux, variables are classified into two main types: 246 | 247 | 1) System Variables (Environment Variables) 248 | -> These are predefined by the system and available for all users and processes. 249 | -> They store essential system information such as current user, shell path, and executable directories. 250 | -> System variables are usually written in UPPERCASE. 251 | 252 | Examples of System Variables 253 | Run these commands in the terminal to check system variables: 254 | 255 | echo $SHELL # Shows the current shell being used (e.g., /bin/bash) 256 | echo $USER # Displays the current logged-in user 257 | echo $PATH # Lists directories where system searches for executable files 258 | πŸ“Œ To view all system variables, use: 259 | 260 | env 261 | 262 | 2) User-Defined Variables 263 | -> These are custom variables created by users to store values for their scripts or tasks. 264 | -> They are not available globally unless exported. 265 | -> By convention, they are written in lowercase. 266 | 267 | Example of User-Defined Variables 268 | 269 | name=Pankaj 270 | id=101 271 | age=25 272 | gender=male 273 | 274 | To access these variables, use: 275 | 276 | echo $name # Output: pankaj 277 | echo $id # Output: 101 278 | echo $age # Output: 25 279 | 280 | 🚨 Important: Do not add spaces before or after = while assigning a variable (e.g., name = pankaj ❌ will cause an error). 281 | 282 | Why to use export keyword to create variable in shell script: 283 | -> To access a variable from one script file into another we should use export keyword. 284 | 285 | Example: Demonstrating export 286 | Step 1: Create Parent Script (parent.sh) 287 | 288 | #!/bin/bash 289 | export MESSAGE="Hello from Parent" 290 | ./child.sh 291 | 292 | Step 2: Create Child Script (child.sh) 293 | 294 | #!/bin/bash 295 | echo "Child received: $MESSAGE" 296 | 297 | Step 3: Run the Parent Script 298 | 299 | chmod +x parent.sh child.sh # Give execution permission 300 | ./parent.sh 301 | 302 | ###################################### 303 | Setting Variables Permanently in Linux 304 | ###################################### 305 | 306 | To make environment variables persistent, we store them in the .bashrc file. This ensures the variables are available even after restarting the terminal or system. 307 | 308 | Steps to Set Permanent Variables 309 | 310 | 1) Locate the .bashrc File 311 | 312 | The .bashrc file is a hidden file located in the user's home directory. 313 | To check if the file exists, run: 314 | 315 | ls -la 316 | 317 | To view its content: 318 | 319 | cat ~/.bashrc 320 | 321 | 2) Open the .bashrc File for Editing 322 | Use the vi or nano editor to modify the file: 323 | 324 | vi ~/.bashrc 325 | (or use nano ~/.bashrc if you prefer nano editor.) 326 | 327 | 3) Add Variables at the End of the File 328 | Scroll to the bottom of the file and add the following lines: 329 | 330 | 331 | export COURSE=devops 332 | export TRAINER=pankaj 333 | 334 | βœ… Changes made here will persist across terminal sessions. 335 | 336 | 4) Apply the Changes 337 | After editing, save and exit (ESC β†’ :wq in vi, or CTRL + X β†’ Y β†’ Enter in nano). 338 | 339 | Then, apply the changes immediately by running: 340 | 341 | source ~/.bashrc 342 | 343 | 5) Access the Variables 344 | Now, check if the variables are set: 345 | 346 | echo $COURSE 347 | echo $TRAINER 348 | 349 | Expected Output: 350 | 351 | devops 352 | pankaj 353 | 354 | Key Points 355 | -> Every user has their own .bashrc file in their home directory (/home/username/.bashrc). 356 | -> Changes in .bashrc apply only to that user. 357 | 358 | ################################################ 359 | How to Set Variables for All Users in Linux? 360 | ################################################ 361 | 362 | By default, variables set in .bashrc are user-specific. However, to make variables available system-wide (for all users), you need to define them in global configuration files such as /etc/profile or /etc/environment. 363 | 364 | 1) Setting Variables in /etc/profile 365 | /etc/profile is a global shell configuration file executed for all users when they log in. 366 | 367 | Adding variables here ensures they are available system-wide for all users. 368 | 369 | Steps to Set System-Wide Variables in /etc/profile 370 | Step 1: Open /etc/profile with a text editor 371 | 372 | sudo vi /etc/profile 373 | (Use nano /etc/profile if you prefer nano.) 374 | 375 | Step 2: Add the Variables at the End of the File 376 | 377 | export COURSE=devops 378 | export TRAINER=pankaj 379 | 380 | 381 | Step 3: Apply Changes Immediately 382 | Run: 383 | 384 | 385 | source /etc/profile 386 | This ensures the changes take effect without needing a reboot. 387 | 388 | Step 4: Verify the Variables 389 | 390 | echo $COURSE 391 | echo $TRAINER 392 | 393 | βœ… Output: 394 | 395 | devops 396 | pankaj 397 | 398 | ########################################## 399 | Operators in Linux Shell Scripting 400 | ########################################## 401 | 402 | -> Operators are symbols that perform operations on variables or values. For example: 403 | 404 | Example: 405 | 406 | echo $((10 + 20)) # Output: 30 407 | 408 | 409 | 1) Arithmetic Operators in Shell 410 | Operator Description Example (a=10, b=5) 411 | + Addition echo $((a + b)) β†’ 15 412 | - Subtraction echo $((a - b)) β†’ 5 413 | * Multiplication echo $((a * b)) β†’ 50 414 | / Division echo $((a / b)) β†’ 2 415 | % Modulus (Remainder) echo $((a % b)) β†’ 0 416 | 417 | How It Works 418 | $(( ... )): This syntax tells Bash to evaluate the mathematical expression inside the parentheses. 419 | 420 | 421 | πŸ“Œ Example: 422 | 423 | FNUM=10 424 | SNUM=5 425 | 426 | echo $((FNUM + SNUM)) # Addition β†’ 15 427 | echo $((FNUM - SNUM)) # Subtraction β†’ 5 428 | echo $((FNUM * SNUM)) # Multiplication β†’ 50 429 | echo $((FNUM / SNUM)) # Division β†’ 2 430 | echo $((FNUM % SNUM)) # Modulus β†’ 0 431 | 432 | 433 | 3) Handling Decimal Values (Floating-Point Arithmetic) 434 | 435 | -> The default $(()) does not support floating-point calculations. 436 | -> To handle decimals, use bc (Basic Calculator) command is used for floating-point arithmetic 437 | 438 | echo "10.5 + 2.3" | bc # Output: 12.8 439 | echo "10 / 3" | bc -l # Output: 3.333333333 440 | 441 | πŸ“Œ bc -l enables floating-point calculations. 442 | 443 | ##################################################### 444 | Complete List of Relational Operators in Bash (used for numbers only) 445 | ##################################################### 446 | Operator Description Example 447 | -eq Equal to [ 5 -eq 5 ] β†’ true 448 | -ne Not equal to [ 5 -ne 3 ] β†’ true 449 | -gt Greater than [ 10 -gt 5 ] β†’ true 450 | -lt Less than [ 3 -lt 8 ] β†’ true 451 | -ge Greater than or equal to [ 10 -ge 10 ] β†’ true 452 | -le Less than or equal to [ 4 -le 7 ] β†’ true 453 | 454 | #################################################### 455 | 1. Space Around Square Brackets [ condition ] 456 | -> In Bash, when using the if condition, there must be spaces around the square brackets [ ]. 457 | -> Bash treats [ as a command. 458 | -> The condition inside must be separated by spaces; otherwise, Bash will treat [$NUM-gt10] as a single argument and throw an error. 459 | 460 | Note: shell treats everything as a string by default, unless explicitly told otherwise. 461 | 462 | ------------------------------------- 463 | ❌ Incorrect: 464 | if [$NUM-gt10 ]; then 465 | ---------------------------------------- 466 | -------------------------------------- 467 | βœ… Correct: 468 | if [ "$NUM" -gt 10 ]; then 469 | -------------------------------------- 470 | Why? 471 | 472 | #################################################### 473 | 2. Space Between the if, elif, and then Keywords 474 | #################################################### 475 | 476 | -> The then keyword must be on the same line as if or a newline. 477 | -> If it is on the same line, it must be separated by a semicolon (;). 478 | 479 | -------------------------------------------------- 480 | βœ… Correct: 481 | if [ "$NUM" -gt 10 ]; then 482 | OR 483 | if [ "$NUM" -gt 10 ] 484 | then 485 | ----------------------------------------------------- 486 | ❌ Incorrect: 487 | if [ "$NUM" -gt 10 ]then 488 | ----------------------------------------------------- 489 | ################################################## 490 | 3. Space Around Operators (-gt, -eq, -lt, etc.) 491 | ################################################### 492 | Comparison operators like -gt, -eq, -lt, etc., should have spaces before and after them. 493 | ---------------------------------------------------------- 494 | βœ… Correct: 495 | if [ "$NUM" -gt 10 ]; then 496 | ----------------------------------------------------------- 497 | ❌ Incorrect: 498 | if [ "$NUM"-gt10 ]; then 499 | ------------------------------------------------------------ 500 | 501 | πŸ§ͺ Example 1: Using (( ... )) β€” Arithmetic Style (Modern & Clean) 502 | x=2 503 | if (( x > 1 )); then 504 | echo "Using (( ... )): x is greater than 1 β†’ $x" 505 | fi 506 | 507 | βœ… How it works: 508 | -> (( ... )) is bash arithmetic context 509 | -> x > 1 is treated like a math expression (like in C or Java) 510 | -> You don’t need $ inside (( ... )), but it works either way 511 | 512 | πŸ§ͺ Example 2: Using [ ... ] β€” Classic Style (More Compatible) 513 | 514 | x=2 515 | if [ $x -gt 1 ]; then 516 | echo "Using [ ... ]: x is greater than 1 β†’ $x" 517 | fi 518 | 519 | βœ… How it works: 520 | -> [ ... ] is the test command 521 | -> -gt means β€œgreater than” for numbers 522 | -> $x is required to access the value 523 | -> Spaces are mandatory before and after [ 524 | 525 | Note: ❌ You CANNOT use -ge (or -gt, -lt, etc.) inside (( ... )) 526 | 527 | 528 | 529 | ################################################### 530 | String Comparison Operators (Used with [[ ... ]]) 531 | ################################################### 532 | 533 | When comparing strings, use the following operators: 534 | 535 | Operator Meaning Example 536 | == Equal to [[ "$str1" == "$str2" ]] 537 | != Not equal to [[ "$str1" != "$str2" ]] 538 | > Greater (alphabetically) [[ "$str1" > "$str2" ]] 539 | < Less (alphabetically) [[ "$str1" < "$str2" ]] 540 | 541 | 542 | 🚨 Important Notes: 543 | a. > and < work for string comparison inside [[ ... ]] but not in [ ... ]. 544 | b. Always use quotes around string variables to prevent errors 545 | 546 | Example 1: 547 | ------------ 548 | echo "Enter a number:" 549 | read num 550 | 551 | if [ "$num" -gt 0 ]; then 552 | echo "The number is positive." 553 | fi 554 | 555 | Example 2: 556 | ------------ 557 | #!/bin/bash 558 | 559 | echo "Enter a number:" 560 | read num 561 | 562 | if [ "$num" -gt 0 ]; then 563 | echo "Positive number." 564 | else 565 | echo "Zero or negative number." 566 | fi 567 | 568 | Example 3: 569 | ------------ 570 | #!/bin/bash 571 | 572 | echo "Enter a number:" 573 | read num 574 | 575 | if [ "$num" -gt 0 ]; then 576 | echo "Positive" 577 | elif [ "$num" -lt 0 ]; then 578 | echo "Negative" 579 | else 580 | echo "Zero" 581 | fi 582 | 583 | ################################### 584 | πŸ” Looping in Shell Scripting 585 | ################################### 586 | 587 | Loops are used to repeat a block of code multiple times. There are mainly two types: 588 | 589 | a. Range-Based Loop – for loop 590 | 591 | b. Condition-Based Loop – while loop 592 | 593 | Syntax: 594 | 595 | for(( initialization; condition; increment/decrement )) 596 | do 597 | # statements 598 | done 599 | 600 | βœ… Explanation: 601 | 602 | for (( ... )) – this is the arithmetic format of the for loop (like in C/C++). 603 | 604 | initialization – usually a variable like i=1 605 | 606 | condition – a check like i<=10 607 | 608 | increment – update variable like i++ 609 | 610 | NO SPACES around the (( ... )) 611 | SPACES are needed after do and before done 612 | 613 | Note: 614 | --------- 615 | ((...)) Performs arithmetic operations only (no output) ((i++)) 616 | $((...)) Performs arithmetic and returns the result (used in expressions) echo $((2 + 3)) 617 | 618 | Note: 619 | --------------------------------------- 620 | πŸ› οΈ The problem: 621 | [ ... ] is used for conditions, like in if or while, not in for loops. 622 | 623 | NOte: 624 | -------------------------------------------- 625 | βœ… In (( ... )) β€” NO need for $ with variables 626 | bash 627 | Copy 628 | Edit 629 | i=5 630 | if (( i < 10 )); then 631 | echo "Yes, i is less than 10" 632 | fi 633 | (( ... )) is for arithmetic. 634 | 635 | Inside, you can use variables directly without $. 636 | 637 | It's like writing math in C or Java. 638 | 639 | βœ”οΈ Both of these are OK: 640 | 641 | -> (( i < 10 )) #valid 642 | -> (( $i < 10 )) # also valid but $ is optional 643 | -> ❗ In [ ... ] β€” You MUST use $ with variables 644 | ------------------------------------------------------ 645 | i=5 646 | if [ $i -lt 10 ]; then 647 | echo "Yes, i is less than 10" 648 | fi 649 | ------------------------------------------------------ 650 | -> [ ... ] treats everything as strings/commands. 651 | -> So, you need to dereference the variable using $. 652 | -------------------------------------------------------------------- 653 | ❌ This will NOT work: 654 | if [ i -lt 10 ]; then # i is just a string here, not the variable! 655 | ---------------------------------------------------------------------- 656 | βœ”οΈ Correct way: 657 | if [ $i -lt 10 ]; then 658 | ---------------------------------------------------------------------- 659 | 660 | 661 | Example 1: 662 | ----------- 663 | 664 | #! /bin/bash 665 | 666 | for(( i=1; i<=20; i++ )) 667 | do 668 | if(( i%2 != 0 )); then 669 | echo $i 670 | fi 671 | done 672 | 673 | Example 2: 674 | ------------ 675 | πŸ”Ή Example 2: Print Multiples of 5 from 1 to 50 676 | 677 | #! /bin/bash 678 | 679 | for(( i=1; i<=50; i++ )) 680 | do 681 | if(( i%5 == 0 )); then 682 | echo $i 683 | fi 684 | done 685 | 686 | Syntax 687 | -------------- 688 | 689 | while [ condition ] 690 | do 691 | # statements 692 | done 693 | 694 | NOte: 695 | -------- 696 | Example using ((...)): 697 | 698 | i=1 699 | while (( i <= 5 )) 700 | do 701 | echo "Number: $i" 702 | ((i++)) 703 | done 704 | 705 | βœ” This is equivalent to: 706 | 707 | i=1 708 | while [ $i -le 5 ] 709 | do 710 | echo "Number: $i" 711 | ((i++)) 712 | done 713 | 714 | ------------------------------------------- 715 | 716 | 717 | Example 1: 718 | ----------- 719 | Print Even Numbers from 1 to 20 using While Loop 720 | 721 | #! /bin/bash 722 | 723 | i=1 724 | while [ $i -le 20 ] 725 | do 726 | if (( i%2 == 0 )); then 727 | echo $i 728 | fi 729 | ((i++)) 730 | done 731 | 732 | Example 2: 733 | ----------- 734 | Print Table of 2 using While Loop 735 | 736 | #! /bin/bash 737 | 738 | i=1 739 | while [ $i -le 10 ] 740 | do 741 | echo $((2 * i)) 742 | ((i++)) 743 | done 744 | 745 | Example 3: 746 | -------------- 747 | Sum of Numbers from 1 to 10 using While Loop 748 | 749 | #! /bin/bash 750 | 751 | i=1 752 | sum=0 753 | while [ $i -le 10 ] 754 | do 755 | sum=$((sum + i)) 756 | ((i++)) 757 | done 758 | 759 | echo "Sum is: $sum" 760 | 761 | ################################ 762 | Function 763 | ############################### 764 | 765 | What is a Function in Shell Script? 766 | -------------------------------------- 767 | A function is a block of code that performs a specific task. Once defined, you can call it multiple times whenever needed 768 | 769 | syntax: 770 | 771 | function function_name() { 772 | # your commands 773 | } 774 | 775 | or 776 | 777 | function_name() { 778 | # your commands 779 | } 780 | 781 | method calling syntax: 782 | ---------------------------- 783 | function_name 784 | 785 | Example 1: 786 | ----------- 787 | 788 | #! /bin/bash 789 | 790 | welcome() { 791 | echo "Welcome" 792 | } 793 | 794 | # Function call 795 | welcome 796 | 797 | Example 2: 798 | ----------- 799 | 800 | #! /bin/bash 801 | 802 | greet_user() { 803 | echo "Hello, $1!" 804 | echo "You are learning $2." 805 | } 806 | 807 | # Call function with arguments 808 | greet_user "John" "Shell Scripting" 809 | 810 | Example 3: 811 | ------------- 812 | 813 | #! /bin/bash 814 | 815 | sum() { 816 | result=$(($1 + $2)) 817 | echo "Sum is: $result" 818 | } 819 | 820 | sum 10 25 821 | 822 | Example 4: 823 | ---------- 824 | 825 | #! /bin/bash 826 | 827 | sum() { 828 | echo "Sum: $(($1 + $2))" 829 | } 830 | 831 | subtract() { 832 | echo "Difference: $(($1 - $2))" 833 | } 834 | 835 | # Use cmd args for calculation 836 | sum $1 $2 837 | subtract $1 $2 838 | 839 | βœ… Benefits of Using Functions 840 | βœ” Code reuse 841 | βœ” Easier to test/debug 842 | βœ” Logical separation of tasks 843 | βœ” Can take parameters (just like mini scripts) 844 | 845 | ############################################# 846 | βœ… What is Scheduling in Linux? 847 | ############################################# 848 | 849 | -> Scheduling means setting up a task to run automatically at a specific time β€” without needing manual execution. 850 | 851 | -> Instead of you running a script, the system runs it for you β€” automatically, at a fixed time or repeating interval. 852 | 853 | ############################# 854 | 🧰 Why Use Scheduling? 855 | ############################# 856 | In real-time environments (like DevOps, system admin, cloud, etc.), many tasks need to be automated: 857 | 858 | πŸ—‘οΈ Deleting temp or log files regularly 859 | 860 | πŸ—‚οΈ Backing up data daily or weekly 861 | 862 | πŸ–₯️ Monitoring system health 863 | 864 | πŸ“§ Sending reports via email 865 | 866 | πŸ› οΈ Running maintenance scripts 867 | 868 | ####################################### 869 | πŸ•’ How Do We Schedule in Linux? 870 | ######################################## 871 | 872 | -> We use a tool called cron (short for chronograph) which allows you to schedule tasks using cron jobs. 873 | 874 | ########################### 875 | πŸ“„ What is a Cron Job? 876 | ########################### 877 | 878 | -> A cron job is a command or script scheduled to run at a particular time using the cron service. 879 | 880 | -> You define cron jobs in a file called a crontab (short for β€œcron table”). 881 | 882 | ############################### 883 | Install CRON in Amazonlinux 884 | ############################## 885 | 886 | sudo yum install cronie 887 | sudo systemctl enable crond 888 | sudo systemctl start crond 889 | 890 | 891 | πŸ“ Example Requirement: 892 | You want to run the script system-health-check.sh every day at 9:00 AM. 893 | 894 | βœ… Step-by-Step: 895 | Open the crontab editor: 896 | crontab -e 897 | 898 | Add this line: 899 | 0 9 * * * /path/to/system-health-check.sh 900 | 901 | πŸ“… Cron Time Format: 902 | 903 | 🌟 * * * * * = Every Minute 904 | Each asterisk * represents a unit of time, in this order: 905 | 906 | Position Field Meaning Example 907 | 1️⃣ Minute 0–59 * = every minute 908 | 2️⃣ Hour 0–23 (24h clock) * = every hour 909 | 3️⃣ Day of Month 1–31 * = every day 910 | 4️⃣ Month 1–12 * = every month 911 | 5️⃣ Day of Week 0–7 (0 or 7 = Sunday) * = every day 912 | So in 0 9 * * *, it means: 913 | 914 | 0 minute 915 | 916 | 9 hour 917 | 918 | Every day, month, and weekday 919 | 920 | Example 1: 921 | --------- 922 | ▢️ 2. Every 5 Minutes 923 | */5 * * * * 924 | 925 | ▢️ 3. Every Day at 9:00 AM 926 | 0 9 * * * 927 | 928 | ▢️ 4. Every Day at 6:30 PM 929 | 30 18 * * * 930 | 931 | ▢️ 5. Every Monday at 8:00 AM 932 | 0 8 * * 1 933 | 934 | ▢️ 6. Run job everyday @4:15 PM Monday - Friday 935 | 15 16 * * 1-5 936 | 937 | ▢️ 6. Every 2 Hours 938 | 0 */2 * * * 939 | 940 | 941 | 942 | --------------------------------------------------------------------------------