• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 224
  • Last Modified:

correct expansion of ~ char in a bash script

Hello-

I'm writing a simple bash script to back up user accounts on a Linux machine. I want to pass the user name into the script as an argument and then expand it to the full home path for the user. In other words, I want to inside the
script do something like:

cd ~user1

This style works fine in the script. However, I need to be able to pass the user name in as an argument, so I'm trying to do:

cd ~$1

This doesn't expand correctly.

How do I get the desired expansion using the argument?

Thanks,

Paul T.
0
titchener
Asked:
titchener
1 Solution
 
sdussingerCommented:
Years ago there used to be a program on Unix called 'glob' which would expand paths like this. It appears that this program has been subsumed into the shell in Linux, so just calling that is not an option. Instead, try these on for size. There are two different ways to do it (1 clean and simple, the other a vicious hack)....

-----------------------------------------------------------
#!/bin/bash

#Version 1
#Extract the home directory for the user from the passwd file.
DIR=`cat /etc/passwd | grep $1 | awk -F: '{print $6}'`
echo Changing to: $DIR
cd $DIR
pwd

#Version 2
#This one is a hack. Create a subshell and let it expand the
#arguments for us. After expansion, it changes to the home
#directory, which we print and store back in the parent
#shell. Once the parent shell know the directory to go to
#it can just cd itself.
DIR=`bash -c "cd ~$1;pwd"`
echo Changing to: $DIR
cd $DIR
pwd

-----------------------------------------------------------
Both of these approaches work on my machine (Mandrake 7.2 running bash-2.04-12.

HTH

--Steve
0
 
ahoffmannCommented:
dir="~$1"
eval cd $dir
0
 
paulqnaCommented:
Putting the ~$1 like ~${1} could help. (ksh solution anyway)
0
NEW Veeam Backup for Microsoft Office 365 1.5

With Office 365, it’s your data and your responsibility to protect it. NEW Veeam Backup for Microsoft Office 365 eliminates the risk of losing access to your Office 365 data.

 
ahoffmannCommented:
which ksh does this do?
0
 
titchenerAuthor Commented:
Thanks, that did the job.
0
 
paulqnaCommented:
/bin/ksh ;)

No comment...
0
 
ahoffmannCommented:
paulqna, I meant the version, like pdksh, (AT&T) ksh
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now