…with an open minded approach

Posts tagged “arguments

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.

 


#!/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