DEV Community

Discussion on: Bash Script Tool Kit

Collapse
 
moopet profile image
Ben Sinclair

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
fi

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

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.

Thread Thread
 
jimmymcbride profile image
Jimmy McBride

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