Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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:

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

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


This does not work:

$ cat
ls $(~$USER)

$ sh -x
+ USER=user1
+ ~user1 1: ~user1: not found
+ ls
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
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
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
up vote 5 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: – 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)

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .