Bash ==== Bash ---- Shebang ^^^^^^^ The shebang line tells the system which interpreter to use to execute the script: .. code-block:: bash #!/bin/bash Variables ^^^^^^^^^^^^^^ Define and use variables: .. code-block:: bash name="Bob" echo "Hello world, $name!" User input ^^^^^^^ Read user input: .. code-block:: bash echo "What is your name?" read name echo "Hello, $name!" For loop -------- Iterate through a range: .. code-block:: bash for i in {1..5}; do echo "Number $i" done Conditional statements ^^^^^^^ Use conditional logic: .. code-block:: bash echo "Enter a number:" read num if [ $num -lt 10 ]; then echo "The number is less than 10." else echo "The number is 10 or greater." fi Comparison operators: - ``-lt`` for "less than" - ``-gt`` for "greater than" - ``-eq`` for "equals" - ``-ne`` for "not equal" - ``-le`` for "less than or equal to" - ``-ge`` for "greater than or equal to" While loop ^^^^^^^ Loop while a condition is true: .. code-block:: bash counter=1 while [ $counter -le 5 ]; do echo "Counter is $counter" ((counter++)) done Functions --------- Define and call functions: .. code-block:: bash intro() { echo "Hi $1! You are $2 years old." } intro "Bob" 30 Folder and file management --------------------------- Loop through directories with argument validation: .. code-block:: bash # $# is a special variable giving the number of arguments if [ "$#" -ne 1 ]; then echo "Usage: $0 /path/to/directory" exit 1 fi # Use the first argument as the root directory root_dir="$1/*" # Loop through each item in the root directory for dir in $root_dir; do if [ -d "$dir" ]; then # Check if it's a directory echo "Visiting directory: $dir" # Perform operations in "$dir" fi done To use, run: .. code-block:: bash ./script.sh /path/to/directory Verify a file exists before proceeding: .. code-block:: bash # Check if a file exists if [ ! -f "my_file.txt" ]; then echo "Error: File does not exist." exit 1 fi .. note:: ``exit 1`` (or any non-zero value) indicates that the script terminated with an error. A successful script should ``exit 0`` or simply exit without a code. Common file test operators ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - ``-f file`` - True if file exists and is a regular file - ``-d dir`` - True if dir exists and is a directory - ``-e path`` - True if path exists (file or directory) - ``-r file`` - True if file exists and is readable - ``-w file`` - True if file exists and is writable - ``-x file`` - True if file exists and is executable