Bash and the empty optional arguments on command line
Rédigé par gorki Aucun commentaireProblem :
Well, I know that having named parameter is better “-file=”
etc..
But for a simple task, I wanted to give :
./mycommand arg1 arg2 ‘’ ‘’ arg5
And pass those parameters to a function…
Solution :
Not so lost in internet but easy to do at the end !
So basically, as simple as :
# Solution OK : use arrau
all_args=("$@");
myfunction "${all_args[@]}"
# Loop over parameters
for i in "${@}"; do
echo "$i"
done
for i in "${all_args[@]}"; do
echo "$i"
done
From :
#!/bin/bash
all_args=("$@");
myfunction() {
arg1=$1
arg2=$2
arg3=${3:-'default3'}
arg4=${4:-'default4'}
arg5=${5:-'default5'}
echo "arg1=$arg1"
echo "arg2=$arg2"
echo "arg3=$arg3"
echo "arg4=$arg4"
echo "arg5=$arg5"
}
echo "--------------- args hard-codede"
myfunction 1 2 "" "" yes
echo "--------------- explode array with quote"
myfunction $(printf ""%s" " "${all_args[@]}")
echo "--------------- working just expand array"
myfunction "${all_args[@]}"
With the following command line :
./test.sh 1 2 "" "" yes
--------------- args hard-codede
arg1=1
arg2=2
arg3=default3
arg4=default4
arg5=yes
--------------- explode array with quote
arg1="1"
arg2="2"
arg3=""
arg4=""
arg5="yes"
--------------- working just expand array
arg1=1
arg2=2
arg3=default3
arg4=default4
arg5=yes