Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change script directory to user's homedir in a shell script

Tags:

linux

bash

shell

In my bash script I need to change current dir to user's home directory.

if I want to change to user's foo home dir, from the command line I can do:

cd ~foo

Which works fine, however when I do the same from the script it tells me:

./bar.sh: line 4: cd: ~foo: No such file or directory

Seams like it would be such a trivial thing, but it's not working. What's the problem here? Do I need to escape the "~" or perhaps missing quotes or something else?

Edit

when I say user I don't mean current user that runs the script, but in general any other user on the system

Edit

Here is the script:

#!/bin/bash

user="foo"
cd ~$user

if username is hardcoded like

cd ~foo

it works, but if it is in the user variable then it doesn't. What am I missing here?

like image 708
Sergey Golovchenko Avatar asked Feb 06 '09 17:02

Sergey Golovchenko


2 Answers

What about

cd $(getent passwd foo | cut -d: -f6)

and

USER=foo
eval cd ~$USER

works, too (foo is the username)

like image 187
Johannes Weiss Avatar answered Nov 12 '22 07:11

Johannes Weiss


Change it to:

cd $HOME

Actually, I'm not sure why cd ~whatever wouldn't work. I've just tested with a small script and it worked fine:

#!/bin/bash

cd ~sbright

I actually get the same error message that you do when the specified user does not exist on the system. Are you sure (and yes, I know this is one of those is-it-plugged-in questions) that the user exists and has a valid home directory specified?

Edit:

Now that I see what you are actually doing... tilde expansion happens before variable interpolation, which is why you are getting this error.

like image 44
Sean Bright Avatar answered Nov 12 '22 08:11

Sean Bright