0

I am puzzled about the variable substitution in shell scripting. Here is the deal: I have following script.

if [ -d ~someone/Desktop ]
then
    echo exist
fi

which would determine whether user "someone" has "Desktop" directory under his home directory. However, if I substitute the someone by other variable, it will not be correct. See below,

var=someone
if [ -d ~${var}/Desktop ]
then
    echo exist
fi

Although the user "someone" has Desktop directory, it will not print exist in the output. Can someone tell me why this happened?

2 Answers 2

1
var=someone
if [ -d $(eval echo ~${var})/Desktop ]
then
    echo exist
fi
Sign up to request clarification or add additional context in comments.

Comments

0

~user is a special expression that is interpreted by the shell (for explanation, see man bash -> Tilde Expansion). In your case the tilde isn't followed by a user name, so normal variable expansion takes place, ~$var expands to a literal ~someone, not to the usual /home/of/someone.

The quickest way of getting the user's home directory would be to grep it from /etc/passwd:

grep "^$var:" /etc/passwd | cut -d: -f6

Comments

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.