The following blog post shows a sample bash script covering some inportant aspects in writing a bash 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
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
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