Chris Chris - 4 months ago 8
Bash Question

Bash substitute variable in command

myDir = 'apple'

If I have the above variable, what functionality can I use to use it within a command? (I'm guessing it's some type of substitution - so I'd like to know what it's called if so)

How could I use the above variable to do an
ls /home/applefruit
, as obviously
ls /home/$myDirfruit
does not work.


First of all, your variable declaration is not right. There must be no spaces around = in declaration:


Now, ls /home/$myDirfruit did not work because myDirfruit is being treated as the variable name instead of just myDir. You need to use {} to enclose the variable name when the name is being followed by valid variable name constituent character:

ls /home/${myDir}fruit

would be expanded to:

ls /home/applefruit

Also if you have spaces in variable name e.g. myDir='foo bar', use quotes around variable:

ls /home/"${myDir}"fruit