TIL - Bash edition
Table of Contents
Assign script output to a variable
In Bash, we can assign the output of a script to a variable.
currentBranch=$(git rev-parse --abbrev-ref HEAD)
In this example, we assign the current branch name to the currentBranch
variable. By enclosing the script in $()
, we can assign the script’s output to the variable.
Check if a dependency is installed
In Bash, we can check if a dependency is installed.
if command -v jq &> /dev/null; then
:
else
echo "jq is not installed. Please install jq."
exit 1
fi
The command -v jq
part of the script uses the command
built-in shell command with the -v
option to check if jq
is installed and can be executed. The command
built-in is used to determine the location of executables and returns the path to the executable if it exists.
The &> /dev/null
part redirects both the standard output (stdout) and standard error (stderr) of the command -v jq
command to /dev/null
, effectively discarding any output. This is done to suppress any messages that might be printed to the terminal, ensuring that the check is silent.
If statements in Bash
In Bash, we can use if
statements to check for conditions.
if [ "$currentUser" = "guest" ]; then
echo "Only admin can access this script"
exit 1
fi
A fuller example can also deal with elif
and else
:
if [[ "$currentUser" = "admin" ]]; then
# Do something adminy
elif [[ "$currentUser" = "subscriber" ]]; then
# Do something subscribery
else
# Do something else
fi