03 - Shebang

Shebang

  • The shebang (#!) is a special character sequence at the very beginning of a script file that tells the operating system which interpreter should be used to execute the script.

Syntax

#!/path/to/interpreter
  • #: The comment character.

  • !: Indicates the start of the shebang.

  • /path/to/interpreter: The full path to the interpreter binary (e.g., /bin/bash, /usr/bin/python).

Bash Script (bash)

#!/bin/bash
  • The script uses the Bash interpreter (/bin/bash).

Python Script (py)

#!/usr/bin/python3
  • The script uses the Python 3 interpreter (/usr/bin/python3).

Shell Script (sh)

#!/bin/sh
  • The script uses the sh shell interpreter (/bin/sh).

Key Points

  1. Mandatory for Direct Execution:

    • A script with a shebang can be executed directly (e.g., ./script.sh) if it has executable permissions:

        chmod +x script.sh
        ./script.sh
      
  2. Default Behavior Without Shebang:

    • If no shebang is present, the script is executed by the user's current shell (e.g., /bin/bash or /bin/sh by default).
  3. Common Interpreter Paths:

    • /bin/bash: Bash shell.

    • /bin/sh: Bourne shell or its compatible version.

    • /usr/bin/python3: Python 3.

    • /usr/bin/env: Finds the interpreter in the environment.


Exit Codes

  • In shell scripting, exit codes (also known as return codes or exit status) indicate the success or failure of a command or script.

Exit Code Conventions

  1. Success (0):

    • An exit code of 0 means the command or script executed successfully without errors.
  2. Failure (Non-Zero):

    • Any non-zero exit code indicates an error or a specific failure condition.

    • Common non-zero codes are typically integers from 1 to 255.

Checking Exit Codes

  1. Using $?:

    • The special variable $? holds the exit code of the last executed command.

        ls /valid/path
        echo "Exit code: $?"  # Output: 0
      
        ls /invalid/path
        echo "Exit code: $?"  # Output: 2 (or another non-zero code depending on the error)
      
  2. Using exit:

    • The exit command is used to manually set an exit code in a script.

        bashCopy code#!/bin/bash
        echo "This is a script."
        exit 1  # Sets the exit code to 1
      

Common Exit Codes

Exit CodeDescription
0Success
1General error
2Misuse of shell built-ins
126Command invoked cannot execute (Permission Denied
127Command not found
128Invalid exit argument
130Script terminated by Ctrl+C (SIGINT)
255Exit status out of range

Functions

  • Function in a shell script is a piece of or block of reusable code that perform specific task.

  • They help to organize code, improve readability, and avoid repetition by encapsulating logic into a single callable unit.

  • When a shell script runs it runs line-by-line. So your Function must always be defined first before calling it, if not then it will give error.

  • The return statement within a function call helps in specifying the exit code for that function. It is just like the exit code for the entire script but in this case it wont exit the script but the function.

Syntax of Functions

There are two common ways to define a function in shell scripting:

  1. Using the function Keyword:

     function function_name() {
         # Commands
     }
    
  2. Without the function Keyword:

     function_name() {
         # Commands
     }
    

Passing Arguments to a Function

  • Function arguments are accessed using $1, $2, ..., $n, where $1 is the first argument, $2 is the second, and so on.

  • $@ or $* can be used to access all arguments.

      #!/bin/bash
    
      sum() {
          echo "Sum: $(($1 + $2))"
      }
    
      sum 5 10  # Calls the function with arguments 5 and 10
    

Returning Values from Functions

  1. Using echo: The output of echo can be captured.

  2. Using return: Return a status code (limited to integers between 0 and 255).

Returning Values with echo:

  • You can retrieve the return value by assigning the function call to a variable, if using echo command.

      #!/bin/bash
    
      square() {
          echo $(($1 * $1))
      }
    
      result=$(square 4)          # Capture the output of the function
      echo "Square: $result"
    

Returning Status Codes with return:

  • return statements are used to return exit status only.

  • It can only returns the numeric value and not the string/text.

  • You cannot retrieve the return value by assigning the function call to a variable, if using return statement, instead use $?.

      #!/bin/bash
    
      is_even() {
          if [ $(($1 % 2)) -eq 0 ]; then
              return 0  # Success
          else
              return 1  # Failure
          fi
      }
    
      is_even 4                                # function call
      if [ $? -eq 0 ]; then
          echo "The number is even."
      else
          echo "The number is odd."
      fi
    

ShellCheck

  • To analyze and identify bugs and area of improvement in your script use shellcheck utility.

      apt-get install shellcheck
    
      OR
    
      yum install shellcheck