Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I can't figure out how to prefix a string (e.g. "user1") with a tilde (~) to produce ~user1 and have that expand to user1's home directory.

Here is what I have now:

USER="user1"
ls ~${USER}
ls: cannot access ~user1: No such file or directory

~user1 is not being expanded. How can I achieve it?

edit

This does not work:

$ cat test.sh
USER="user1"
ls $(~$USER)

$ sh -x test.sh
+ USER=user1
+ ~user1
test.sh: 1: ~user1: not found
+ ls
test.sh
share|improve this question
    
Using /home/user1 is not an option? –  terdon Sep 14 '12 at 15:34
    
Don't use USER it is your name. Instead use lower case variables. –  richard Sep 14 '12 at 15:43
    
why should lower case be preferred? –  bernie Sep 14 '12 at 15:47
2  
so you don't overwrite the built in variables such as USER. USER holds the name of the current user that is executing the command. –  richard Sep 14 '12 at 15:52
1  
yes but do you want to learn them all, and then keep up to date with all new ones. For this reason it is customary to have all local variables in shell scripts as lower-case. –  richard Sep 14 '12 at 16:03

2 Answers 2

up vote 4 down vote accepted

If your user's directory is not simply /home/user, you can use eval in your script (source):

USER_HOME=$(eval echo ~${USER})
echo ${USER_HOME}
share|improve this answer
    
This works. Now, should I prefer eval or bash -c? –  bernie Sep 14 '12 at 15:51
    
On second thought, I think that bash -c will start a new bash process so it will be marginally slower/more resource intensive. –  terdon Sep 14 '12 at 15:58
    
While researching this, I found this link which explains what is happening and why eval is necessary: fvue.nl/wiki/Bash:_Why_use_eval_with_variable_expansion%3F –  bernie Sep 14 '12 at 15:59

This is a general way to get bash to re-evaluate, but the use of eval may be better as it will not spawn a new process. (echo is built into bash so not a new process)

user="user1"
bash -c "ls ~${user}"
share|improve this answer
    
2nd way does not work. see my edit –  bernie Sep 14 '12 at 15:49
    
This works. Now, should I prefer eval or bash -c? –  bernie Sep 14 '12 at 15:52
    
eval is probably more portable as it does not care what the shell's name is. –  richard Sep 14 '12 at 15:58

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.