Question

I know I've run into this problem on my Linux box, but right now I'm on Mac OS X and I need to do the same thing. I want to use pushd and popd to call scripts or binaries in several locations, but I need to keep the same working directory during this time.

This is a test script. I think this is the dumb way I did this beforehand:

cd ~
pushd . 1>/dev/null
cd Documents
NEW_DIR=`pwd`
OLD_DIR=$(`popd`)
cd $OLD_DIR
echo Current directory: `pwd`
echo New directory: $NEW_DIR

Which results in:

$ ./pushpop.sh
./pushpop.sh: line 5: cd: ~: No such file or directory
Current directory: /Users/NobleUplift
New directory: /Users/NobleUplift/Documents

It works, but not without an error.

Was it helpful?

Solution

popd is a command which will pop the top of the directory stack and change your working directory to it, so you don't need to use cd. Hence your pushpop.sh should read like:

#!/bin/bash
cd ~/
pushd . 1>/dev/null
cd Documents
NEW_DIR=`pwd`
popd
echo Current directory: `pwd`
echo New directory: $NEW_DIR

And you'll get output as you desire:

~
Current directory: /home/imp25
New directory: /home/imp25/Documents

Edit following OPs comments

If you want to capture the output of popd without moving directory, it's probably best to interograte the directory stack which pushd adds to and popd pops off. You can view the stack with the command dirs, which will give a list of directories, the first being your current working directory, i.e.:

cd ~
pushd .
cd Documents
pushd .
dirs
~/Documents ~/Documents ~

You can access specific entries in the stack with the +N and -N options to dirs (+N starts counting from the left, -N starts counting from the right). If you want to get the last thing you pushed to the stack it can be accessed with dirs +1.

Modifying your script would give you something like:

cd ~/
pushd . 1>/dev/null
cd Documents
NEW_DIR=`pwd`
OLD_DIR=$(dirs -l +1)
cd $OLD_DIR
echo Current directory: `pwd`
echo New directory: $NEW_DIR

Here $(dirs -l +1) gets the top of the stack you pushed and returns it in long form (expanding ~ to /home/foo for example). I think the error you're getting is around cd not handling ~ as a directory properly, hence the use of the -l option.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top