If I paste these lines into a command prompt on Debian...

DIR=$(mktemp -d -t bbbrtc.XXXXXX) || exit 1
echo "tmpdir = $DIR"
cd "$DIR"

They make a new temp directory, print the directory name, and then pushd into that directory...

root@beaglebone:/tmp/bbbrtc.2mw02x# DIR=$(mktemp -d -t bbbrtc.XXXXXX) || exit 1
root@beaglebone:/tmp/bbbrtc.2mw02x# echo "tmpdir = $DIR"
tmpdir = /tmp/bbbrtc.Grti6K
root@beaglebone:/tmp/bbbrtc.2mw02x# pushd "$DIR"
/tmp/bbbrtc.Grti6K /tmp/bbbrtc.2mw02x ~/bbbphyfix

... as expected.

If I run the exact same commands from inside a shell script...

root@beaglebone:/tmp/bbbrtc.2mw02x# cat test.sh

DIR=$(mktemp -d -t bbbrtc.XXXXXX) || exit 1
echo "tmpdir = $DIR"
pushd "$DIR"

root@beaglebone:/tmp/bbbrtc.2mw02x# ./test.sh
tmpdir = /tmp/bbbrtc.O6yYgf
./test.sh: 5: ./test.sh: pushd: not found

...it generates the "pushd: not found" message.

Why do these commands not work from inside a shell script, and what it the proper way to have a script create a temp dir and then pushd into that new dir?

  • 5
    Your /bin/sh is not the same shell as your interactive shell. May 28, 2018 at 3:24
  • 3
    Change your shebang to #!/bin/bash for example. pushd is not available in POSIX shell.
    – cuonglm
    May 28, 2018 at 3:25
  • @cuonglm Post as answer and I will gratefully accept it! Thanks!
    – bigjosh
    May 28, 2018 at 3:34

1 Answer 1


pushd is a bash command, which is generally not implemented by /bin/sh. To use pushd in a sh script, you would have to provide a script or function with the same functionality.

The idiomatic way of temporarily changing one's working directory for the course of a few commands in a sh script is to do

( cd directory && somecommand )

This would change into directory and execute somecommand if that succeeded. The whole thing is done in a subshell, so the cd will not have any effect on the rest of the script.


( cd directory || exit 1
  command3 )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.