February 20, 2013

A bashism a week: pushing and pop'ing directories

Want to switch back-and-forth between directories in your shell script?
The bashism of this week can be of some help, but for most needs, the cd utility is more than enough.

pushd, popd, and the extra built-in dirs are bashisms that allow one to create and manipulate a stack of directory entries. For a simple, temporary, switch of directories the following code is portable as far as POSIX:2001 is concerned:

cd /some/directory
  touch some files
  unlink others
  # etc
cd - >/dev/null
# We are now back at where we were before the first 'cd'

Which is equivalent to the following, also portable, code:

cd /some/directory
  touch some files
  unlink others
  # etc
cd "$OLDPWD"
# We are now back at where we were before the first 'cd'

Multiple switches can also be implemented portably without storing the name of the directories in variables at the expense of using subshells (and their side-effects).

However, if you think you can solve your problem more conveniently by using "pushd" and "popd" don't forget to document the need of those built-ins and to adjust the shebang of your script to that of a shell that implements them, such as bash.

3 comments:

  1. Replies
    1. I think the idea of this post is to suggest using 'cd -' as replacement.

      For what it’s worth, the Forgotten Shell Of The Month also implements pushd/popd/dirs “just like the Berkeley C Shell”, but the implementation is part of the dot.mkshrc sample file and written in the shell language itself, not part of the shell interpreter, and must thus be copied or sourced.

      That’s mksh by the way, which RaphaĆ«l conveniently forgot in, for example, the last post of this series, to mention… it’s not as if it didn’t have any achievements, such as being the default Android shell…

      Delete
  2. @Tobias

    The first example does have "cd -" in it :^)

    ReplyDelete