tilde expansion with a variable

JD Austin plug-discuss@lists.plug.phoenix.az.us
Wed, 05 Feb 2003 08:45:58 -0700


Lynn David Newton wrote:

>I've known for years that one can't do tilde expansion
>with a variable name, e.g.,
>
>  WHO=joeuser
>  cd ~$WHO
>
>doesn't work, but I have never quite grokked exactly
>why, or whether there is a workaround.
>
>I've written admin scripts where I've had to copy a set
>of master files into some place within the home
>directory tree of a set of users in a loop. I finished
>a complicated one just yesterday, which is why the
>question is on my mind again.
>
>How simple it would be to follow a basic model such as
>shown in this grealy simplified fragment:
>
>  ulist="joeuser bettyboop johndoe"
>  files="one two three"
>  for u in $ulist
>  do
>    cp $files ~$u
>  done
>
>Instead, I've had to determine the user's home
>directory each time by first pulling it out of the
>password file like:
>
>  uhome=$(grep "^$u:" /etc/passwd | cut -d: -f6)
>
>or some such nonsense, which seems like a lot of
>unnecessary overhead.
>
>It's the same in both ksh (which I use predominantly)
>and bash.
>
>Can someone explain what I'm missing about why it's
>that way, and if there is a simple solution I'm
>overlooking?
>
>  
>
~ contains the path of the current users home directory.

$ Foo=~
$ echo $Foo
/home/austin
Say you have a list of users who are all in the same subdirectory (say 
/home) you can do this:

#set file location where files should be transfered from
filedir=/somedirectory
#get the base home dir:
cd ~
cd ..
# You could also do basedir=~/.. but it isnt as clean
basedir=`pwd`
cd $filedir

ulist="joeuser bettyboop johndoe"
files="one two three"
for u in $ulist
do
cp $files $basedir/$u/.
done