bash script handling arguments parameters - ghdrako/doc_snipets GitHub Wiki

$@

"$@" variable in Bash scripting allows you to safely pass all the arguments provided to a script. It preserves the integrity of spaces and special characters in arguments, making it the most reliable way to handle multiple parameters. When writing a Bash script, "$@" ensures that each argument is handled as a separate entity, even if it contains spaces. This is especially important when dealing with file names or arguments that include spaces or special characters.

A simple script to echo all provided arguments safely

#!/bin/#bash 
echo "All arguments passed to the script:"
# "$@" treats each argument separately, even if it has spaces
for arg in "$@"; do
  echo "$arg"
done
$ ./script.sh "file 1.txt" file2.txt "file 3.txt"
All arguments passed to the script:
file 1.txt
file2.txt
file 3.txt

Using "$@" ensures that each argument is treated individually, even when arguments contain spaces. Without the quotes around "$@", arguments with spaces could be broken into multiple arguments.Compare this with using $*, which concatenates all arguments into a single string, splitting them based on spaces. This can lead to errors when handling file names with spaces.

$1,$2...

Each argument passed to the script corresponds to a specific number, with $1 being the first, $2 the second, and so forth.

If fewer arguments are provided than expected, the corresponding variables will be empty.

$0 refers to the script's name or path, while $# gives the total number of arguments passed.Be cautious: when arguments contain spaces, they should be wrapped in quotes when passed to avoid being split into separate arguments.

shift

The shift command in Bash is used to move through positional parameters (arguments) one by one. After shift is executed, the first argument ($1) is removed, and all other arguments are shifted down by one position.

Script to process each argument using shift

#!/bin/bash 
echo "Processing arguments sequentially:"
while [ $# -gt 0 ]; do
echo "Current argument: $1"
shift # Move to the next argument
done
echo "All arguments processed."

You can use shift n to shift by more than one position, where n is the number of positions to shift.After all arguments are shifted out, $# becomes 0, meaning there are no more arguments left to process.