1
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.

1 Answer 1

2

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

myDir='apple'

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
Sign up to request clarification or add additional context in comments.

1 Comment

Just for completeness, the quotes are sufficient when quoting $myDir alone to drop the braces. ls /home/"$myDir"fruit. In general, the braces are the canonical way to expand a parameter, but may be dropped when the name of the parameter remains unambiguous.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.