Shell Scripting Tips - One liner to change to a given users directory - the hard way

| | 2 min read
Recently we had to provide support on a Red Hat Server where there were hundreds of users and the user directories organized into hierarchies. Normally we change to a users directory using cd ~username. We had some extra time on our hands and wanted to play with the /etc/passwd file and tried to use awk to do the same thing. The following one liner will do this the hard way :-)

cd `(cat /etc/passwd|grep username|awk -F ":" '{print $6}')`

The script works as follows. The home folders of all users are listed in the 6th column of the /etc/passwd file. The columns in the file are separated by colons. The 'cat' part will print the contents of the file to stdout which is piped to grep to find the line corresponding to the user. The grep will print just this line to the stdout which is then piped to awk which takes the content of the 6th column and prints it out. This string is passed as the return value from the back-quoted string and cd uses this path to change the directory.

Using this served the purpose but the solution did not look very elegant. So we saved the following to a file /usr/local/bin/cduser

cd `(cat /etc/passwd|grep $1|awk -F ":" '{print $6}')`

and then added the following alias to ~/.bashrc

alias cduser='. /usr/local/bin/cduser'

The alias is required because a change directory command inside a script will only run in its own context and when control is returned to the calling shell the working directory would remain the same. The only way to work around is to source the script instead of executing it and this is done through the alias part. All is well that ends well. Now all we had to do to change to a users directory was to execute

cduser username

which is slightly more longer than cd ~username but you would be more wiser about shell scripting by figuring out the harder way :-).