linux - Inline variable in shell script -
in 1 of requirement, create command @ start of script , fill variable later. example:
# global mylistdir="ls -la $mydair" #now after code want create variable mydair="/data/dir/" #now run taht command on /data/dir echo "$mylistdir"
how can it?
i tried
mylistdir="ls -la `$mydair`"`
but didn't work.
code should stored in functions, not variables. see bashfaq #50 full description of rationale, , bugs caused ignoring rule.
mylistdir() { ls -la "$mydair"; } mydair=/data/dir mylistdir
if absolutely must store code in variable, use eval
:
mylistdir='ls -la "$mydair"' mydair=/data/dir eval "$mylistdir"
...but mind caveats given in bashfaq #48.
the original code proposed in question written follows:
mylistdir="ls -la `$mydair`"`
...now, that's broken several reasons:
- it uses double-quotes on outside, causing expansions performed @ assignment time instead of @ later evaluation time.
- it puts backticks around
$mydair
, causing value of variable as exists @ assignment time string-split, glob-expanded, , run command, output of command (presumably, empty string) substituted in place. - it has trailing, unmatched backtick @ end, making invalid syntax.
Comments
Post a Comment