Command line arguments in bash script

2019-07-19 07:25发布

问题:

I am trying to read command line arguments in bash but I have problems to read on the 10th column Here is my sample script:

#-------------------------------------------------------
#!/bin/bash
an=$2  mn=$4  dy=$6  der=$8  new=$10  sec=(${12} ${13})
echo $an $mn  $dy   $der  $new  $sec 
#--------------------------------------------------------

I have run the above script "test.sh" as

./test.sh -yr cat  -mn Jan  -dy  tuesday  -der tt  -new car -sec 001 001

The output is:

cat Jan tuesday tt -yr0 001

But for variable $new ($10) the answer should have been car but I get -yr0

Any idea why ?

yacob

回答1:

Here is the fix:

#!/bin/bash
an=$2  mn=$4  dy=$6  der=$8  new=${10}  sec="${12} ${13}"
echo $an $mn  $dy   $der  $new  $sec 
  1. Instead of $10, which is "$1" with 0 appended, use ${10}
  2. sec="..." instead of using parentheses, unless you meant to use array


回答2:

new=$10 is giving you $1 (i.e 'yr') appended with 0. You need some braces : ${10}



标签: bash stdin