re: Bash Script Tool Kit VIEW POST


I've never been a fan of pushd for directory stacks, mostly because I get confused with more than one place to return to (which I'll use cd - for) so the benefit is probably lost on me. But one place I wouldn't use them is inside a script, because unless you're careful and trap things to clean up nicely, it'll mess you up if your script exits early.


I've been using them in mine and haven't had any issues so far. What kind of problems can using pushd in a script cause? Also, how do you trap things to clean up when using pushd in your scripts?


What it is, is that if I'm in a "non-trivial" script, and I'm using pushd and popd to keep a stack of where I am, and one function fails - for example, if pushd doesn't succeed because the directory is missing - then all subsequent commands will think I'm in the wrong place and potentially do destructive things.

On the face of it, cd has the same pitfalls, and if everything was defensively programmed, it wouldn't matter:

if ! cd "$path"; then
  # do some recovery

if ! push "$path"; then
  # do some recovery

But if that's what we're doing, we might as well use absolute paths and program defensively everywhere.

By trapping I mean things like this:

trap clean_up EXIT

clean_up() {
  # do whatever we need to put the system back where we left it.

Given that scripts can be sourced as well as executed, changing directory within a script might or might not change the directory of the calling shell.

Sick! That's some pretty cool stuff. I'm going to look into that some more. Thank you for sharing!

Code of Conduct Report abuse