Getting Directory Name from a File's Pathname

When you write shell scripts or functions, sometimes you have a file's absolute pathname but need the parent directory's name. (You might need the parent's name to see if you have write permission in the directory - say, to remove or rename the file.)

If the pathname is stored in a csh shell (not environment) variable, use the modifier :h (). In the Bourne shell, see if your system has the dirname () command. If it doesn't, you can get the GNU version from the Power Tools disc - or use expr () with a regular expression () that gives you everything up to (but not including) the last slash. For example, if the pathname /home/mktg/fred/afile is stored in the shell variable file, these csh and sh commands would store /home/mktg/fred into the variable dir:

% set dir=$file:h $ dir=`dirname "$file"` $ dir=`expr "$file" : '\(.*\)/'`

To handle multiple pathnames, give this regular expression to sed ():

@ 
% ... sed 's@/[^/]*$@@' ...

- JP