I have a script where I am passing commands to processes with an arguments passed from command line and from environment variables as well.
To simplify my use case lets assume my processes are echo
command.
I noticed that variable expansion is more easy for numeric variables $1
passed from command line than for environment variables $VAR
.
For numeric variables I don't need to have white spaces around to make it work, see example below:
f1() {
echo "this is 1 $1 and var $VAR done"
}
VAR=2 f1 1
#this is 1 1 and var 2 done
f2() {
echo "this_is_1_$1_and_var_$VAR_done"
}
VAR=2 f2 1
#this_is_1_1_and_var_
As you can see, if I replace spaces with underlines, then named variable is no longer interpreted while numeric variable still works fine.
I learned how to workaround this limitation by extra quoting
f3() {
echo "this_is_1_$1_and_var_""$VAR"'_done'
}
VAR=2 f3 1
#this_is_1_1_and_var_2_done
The problem is that my script requires quite a lot of substitution in long SQL statements. Putting extra quotes in each places will make it much more difficult to read and maintain. Therefore I would find it useful to mimic command line argument but it (obviously) doesn't work:
1=echo $VAR
$1
Is there any trick I can make it work?
_
is a legal character in variable names - so the shell is looking for a variable namedVAR_done
. Using${VAR}
will resolve that ambiguity. – steeldriver Nov 21 '20 at 16:16