问题
I got a very good response in my last question. The idea was to process N number of inputs from command line, save first 9 to variables and make a string with 10 to onward.
I found this to be the easiest solution.
var1="$1"
var2="$2"
var3="$3"
var4="public"
var5="$5"
var6="''"
var7="$7"
var8="$8"
var9="$9"
var10="$(shift 9; IFS=""; echo "$*")"
echo snmptrap $var1 $var2 $var3 $var4 $var5 $var6 $var7 $var8 $var9 "$var10"
snmptrap $var1 $var2 $var3 $var4 $var5 $var6 $var7 $var8 $var9 "$var10"
The output looks like this...
./snmptas -v 2c -c "" 9.48.85.57 "" 1.3.6.1.4.1.2.6.201.3 s s ABC DDEF EFFF
snmptrap -v 2c -c public 9.48.85.57 '' 1.3.6.1.4.1.2.6.201.3 s s ABCDDEFEFFF
But I wanted $var10 in this form
"ABC DDEF EFFF".
This needs to changed. It's taking the spaces off.
var10="$(shift 9; IFS=""; echo "$*")"
How can I make var10 = "ABC DDEF EFFF"?
Thanks
回答1:
A subshell with echo is not really appropriate there. Better this way:
shift 9
var10="$*"
If you want quotes around that as part of the value, then change the last line to:
var10=\""$*"\"
Unrelated to that, I'm wondering if your treatment for var6
does what you intended. I suspect that this will be closer to what you really intended:
snmptrap $var1 $var2 $var3 $var4 $var5 '' $var7 $var8 $var9 "$var10"
Or this:
var6=
snmptrap $var1 $var2 $var3 $var4 $var5 "$var6" $var7 $var8 $var9 "$var10"
But if my guess is wrong and your original treatment is working as intended then never mind, ignore these remarks.
回答2:
To get the variable var10 to contain quotes, you need something like this:
shift 9
printf -v "var10" '"%s"' "$*"
And, if you want to quote all your variables, such that missing ones have a place, use this:
#!/bin/bash
set -- -v 2c -c "" 9.48.85.57 "" 1.3.6.1.4.1.2.6.201.3 s s ABC DDEF EFFF
for ((i=1;i<=9;i++)); do
printf -v "var$i" '"%s"' "${!i}"
done
shift 9
printf -v "var10" '"%s"' "$*"
echo snmptrap $var{1..10}
To get the script to read the arguments passed instead of the ones written in the code, just comment out the set --
line.
The output will be:
$ ./snmptrap
snmptrap "-v" "2c" "-c" "" "9.48.85.57" "" "1.3.6.1.4.1.2.6.201.3" "s" "s" "ABC DDEF EFFF"
That each parameter has quotes means no problem to use them as input to the script.
来源:https://stackoverflow.com/questions/37428689/string-concatenation-in-bash-with-space-and-putting-quote-around