Skip to content

Instantly share code, notes, and snippets.

@harishkannarao
Last active December 26, 2021 19:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harishkannarao/e81cc2caa0dfd118608f78249bb60ace to your computer and use it in GitHub Desktop.
Save harishkannarao/e81cc2caa0dfd118608f78249bb60ace to your computer and use it in GitHub Desktop.

Bash Script Example

The following blog post shows a sample bash script covering some inportant aspects in writing a bash script.

Important aspects covered in this script:

  • Validate if input arguments are passed
  • Parse positional arguments
  • Handle parameter values with white space
  • Validating the arguments (using regex)
  • While loop to iterate through varargs
  • Usage of unit functions
  • Usage of function that takes inputs and return value
  • Using -e option to fail the script on command execution errors
  • Using -x option to help debugging the script execution
  • Exit the script with success or error status
  • Redirect error messages to error console

Executing the script:

Method 1 (in it's own bash shell)

The script can be executed as

bash calculate.sh --operation add --lhs 2 --rhs 3

This is the simplest way to execute the script because:

  • The script runs in its own shell
  • Doesn't read variables or environment variables from the main shell
  • Doesn't leave traces of variables or changes to environment variables after script completion
  • Needs only read permission to execute the script

Method 2 (in the main shell where it is invoked)

Another way of executing the script is

Set executable permission for the script

chmod u+x calculate.sh

Execute using relative path

./calculate.sh --operation add --lhs 2 --rhs 3

Or Execute using full path

$HOME/scripts/calculate.sh

The difference from the first style is:

  • The script runs in main shell where it is invoked
  • Shares variables or environment variables from the main shell
  • Leave traces of variables or changes to environment variables after script completion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment