With a username passed to a script, find the user's home directory
- by Clinton Blackmore
I am writing a script that gets called when a user logs in and check if a certain folder exists or is a broken symlink. (This is on a Mac OS X system, but the question is purely bash).
It is not elegant, and it is not working, but right now it looks like this:
#!/bin/bash
# Often users have a messed up cache folder -- one that was redirected
# but now is just a broken symlink. This script checks to see if
# the cache folder is all right, and if not, deletes it
# so that the system can recreate it.
USERNAME=$3
if [ "$USERNAME" == "" ] ; then
echo "This script must be run at login!" >&2
exit 1
fi
DIR="~$USERNAME/Library/Caches"
cd $DIR || rm $DIR && echo "Removed misdirected Cache folder" && exit 0
echo "Cache folder was fine."
The crux of the problem is that the tilde expansion is not working as I'd like.
Let us say that I have a user named george, and that his home folder is /a/path/to/georges_home. If, at a shell, I type:
cd ~george
it takes me to the appropriate directory. If I type:
HOME_DIR=~george
echo $HOME_DIR
It gives me:
/a/path/to/georges_home
However, if I try to use a variable, it does not work:
USERNAME="george"
cd ~$USERNAME
-bash: cd: ~george: No such file or directory
I've tried using quotes and backticks, but can't figure out how to make it expand properly. How do I make this work?