Bash Programming
Basics
Start the file using #!/bin/bash
Define a variable by simply using it without $. To use it later, add $ to the beginning.
To assign the outout of a command to a variable, put the command in parenthesis and add the $ to the beginning:
To read an input from user:
You can add a s switch to hide characters.
To get the current directory, use $PWD.
To get the current user, user $USER.
Logical Comparison
To see if two values are equal, simply use "$var1" = "$var2"
To implement a NOT, use !.
To implement an OR, use ||.
To implement an AND, use &&.
Conditional Statements
IF Statement
Syntax
do_this;
elif [ "condition2" ]; then
do_that
else
do_it
fi
For example, to compare the value of variable with a string use:
...
fi
To check is a variable is null use
do_if_variable_is_null
else
do_if_not_null
fi
To check if a folder (or path) exist, use
...
fi
For check if file exists, use -f instead.
SELECT Statement
Syntax
case $opt in
option1)
...
;;
option2)
...
;;
*)
default_action
esac; done
TRY/CATCH Statement
Syntax:
# Function to handle errors
handle_error() {
local error_code=$?
echo "Error occurred with exit code $error_code"
# Add additional error handling logic here
exit $error_code
}
# Set up trap to call the error handling function on any error
trap 'handle_error' ERR
# Your main script logic
main() {
echo "Executing main script logic..."
# Simulating an error
command_that_might_fail
echo "This line will not be reached if the previous command fails."
echo "Script completed successfully."
}
# Call the main function
main
FUNCTION
To define a function, use
...
}
To pass variables to the function, call it using.
Then, inside the function, these variables can be used based on the order they are defined as
y=$2
If you want to define a variable local for a function use
Normal variables defined inside the function are considered global variables.
Parsing Options from Command Line
To read options and their arguments from command line:
case "${option}" in
s)
commands_for_s_option # argument: "${OPTARG}"
;;
r)
commands_for_r_option
;;
f)
commands_for_f_option # argument: "${OPTARG}"
;;
\?)
echo "Error: Invalid option: -$OPTARG"
exit 1
;;
esac
done
In this example, options s and f must have an argument after the option.
However, r does not need an argument.