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.