First: I'm fairly new to bash batch-scripting but have experience in other script and programming languages
Second: I already looked at Meaning of "[: too many arguments" error from if[] (square brackets) but this that was not the solution for my problem.
I'm creating a command-line parser in a bash script. My first attempt actually already works but still has some if-statement code-duplication in the main-loop which I want to solve, so I moved it to the actual parsing-function and then I run into a "[: too many arguments" error which I cannot get solved (adding "" around variables did not work) in a piece of code which does work if I do not move the if.
Note: in the actual code there is one more command-line option, I left that out for 2 reasons:
- shorter listing
- error is seen on all options
The working code looks like this:
arg_str = $@
args=("$@")
arglen=$#
target=some_filename.txt
in_dir=/some_input_dir/
function working_parser()
{
local option=$1
myresult=''
i=0
while [ ${args[i]} != $option -a $i -n $arglen ]
do
i=$((i+1))
done
#TODO add check on $i>arglen
myresult=${args[$((i+1))]}
}
if [[ $arg_str == *'-t'* ]]; then
working_function '-t'
fi
if [[ $myresult != '' ]]; then
target=$myresult
fi
if [[ $arg_str == *'-i'* ]]; then
working_function '-i'
fi
if [[ $myresult != '' ]]; then
in_dir=$myresult
fi
The failing code looks like this (Left out the definitions, since they are the same as for the working code). The '[: too many arguments' error occurs in the while loop, where it did not happen in that same code in the working-version.
function failing_parser()
{
local option=$1
myresult=''
if [[ $arg_str == *$option* ]]; then
i=0
while [ ${args[i]} != $option -a $i -n $arglen ]
do
i=$((i+1))
done
#TODO add check on $i>arglen
myresult=${args[$((i+1))]}
fi
}
failing_parser '-t'
if [[ $myresult != '' ]]; then
target=$myresult
fi
failing_parser '-i'
if [[ $myresult != '' ]]; then
in_dir=$myresult
fi
What am I doing wrong?