bash scripts multiple arguments
Example how to parse multiple arguments, one-by-one, in bash – be aware of the importance of surrounding “$@” and “$ARG_I” within double-quotes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
[[ $# -gt 1 ]] || { echo "Usage: $0 <arg1> <arg2> … <argN>"; exit 255; } | |
echo 'Dont forget to surround the "$@" with the double-quotes '' so that it does not divide arguments that contain spaces.' | |
echo 'Samewise, you also need to surround the "$ARG_I" var' | |
for ARG_I in "$@"; do | |
echo '$@ = '"$@" | |
echo '$ARG_I = '"$ARG_I" | |
done | |
# paulo@lnxp:/tmp$ bash a.sh "Arg1" "I'm argument 2 with spaces" "And Im arg3" | |
# $@ = Arg1 I'm argument 2 with spaces And Im arg3 | |
# $ARG_I = Arg1 | |
# $@ = Arg1 I'm argument 2 with spaces And Im arg3 | |
# $ARG_I = I'm argument 2 with spaces | |
# $@ = Arg1 I'm argument 2 with spaces And Im arg3 | |
# $ARG_I = And Im arg3 | |
# | |
# NOTE: | |
# Dont forget to surround the "$@" with the double-quotes so that it does not divide arguments that contain spaces. | |
# Samewise, you also need to surround the "$ARG_I" var |