Arguments provide a way to configure extra parameters for your script or code. Keep your hands on the wheel when learning about these though, since you're in for quite the ride. Parsing and working with arguments in bash is a bit tedious and you really have to understand the concept.
Arguments in bash can solely be referenced by their position. Arguments are called like other variables using the dollar sign, but are followed by their position to get the argument at that position:
# Our script
...
echo "$1" # "I am the first argument"
echo "$2" # "I am the second argument"
echo "$3" # ""
# Calling our script
./script.sh "I am the first argument" "I am the second argument"
There are two special variables that are useful for code working with arguments:
$#
grabs the amount of arguments provided$@
contains an array/list of argumentsfunction guard_args() {
if [[ "$#" -lt 1 ]]; then
echo "No args passed to function. Exiting..."
exit 1
fi
}
function arg_check() {
echo "No. of arguments: $#" # No. of arguments: 3
echo "Arguments list: $@" # Arguments list: 1 2 function call
}
guard_args "" # Will quit the script because no valid args are supplied
guard_args "1" # Continues to the next line
arg_check "1" 2 "function call"
The list of arguments proves especially useful when calling other functions from a main function or when writing pipelines. This way we can propagate the arguments to the other function:
# script.sh
function pipeline_tests() {
echo "Running tests in folder $1"
./tests.sh "$1"
}
...
function main() {
pipeline_tests "$@" # Otherwise we would need to explicitly pass $1 or other args here to have them available in pipeline_tests
}
main "$@"
...
$ ./script.sh src/__tests__/**/
Arguments can be checked for existence using the -z operator. It verifies that an argument is not a null value (not provided or empty string):
function deploy() {
if [[ -z "$2" ]]; then
echo "Need to provide an environment to deploy to"
exit 1
fi
cloud_provider deploy --env "$@"
}
deploy "europe" "" # Would exit since $2 is null
deploy "europe" "staging" # Passes