Seamless directory navigation in bash
It is time (and brain) consuming to remember and type the directory path if you require to move across directories frequently. You can save some time and energy with three in-built commands supported by bash. They are pushd, popd and dirs.
User can use pushd command in the place of cd comand. When you use pushd command to change directory, bash remembers and pushes the directory name to stack before mobing to specified directory. Later user can use popd to move back to the last remembered directory.
This mechanism operates in the form of stack. That means you can use as many pushd commands to change directories and use equal number of popd to get back to the very first directory where you used pushd command for the first time. At any time user can use dirs command to view the directory stack.
In the following example, pushd is used twice to move from dir1 to dir2 and dir2 to dir3. Then popd is used twice to go back to dir1.
[liz@techpulp ~]# ls dir1 dir2 dir3 [liz@techpulp ~]# cd dir1 [liz@techpulp ~]# pwd /home/neo/demo/dir1 [liz@techpulp ~]# pushd ../dir2 ~/demo/dir2 ~/demo/dir1 [liz@techpulp ~]# pwd /home/neo/demo/dir2 [liz@techpulp ~]# pushd ../dir3 ~/demo/dir3 ~/demo/dir2 ~/demo/dir1 [liz@techpulp ~]# pwd /home/neo/demo/dir3 [liz@techpulp ~]# popd ~/demo/dir2 ~/demo/dir1 [liz@techpulp ~]# pwd /home/neo/demo/dir2 [liz@techpulp ~]# popd ~/demo/dir1 [liz@techpulp ~]# pwd /home/neo/demo/dir1 [liz@techpulp ~]# popd bash: popd: directory stack empty [liz@techpulp ~]#
If you move between only two directories frequently, you can use cd -
command.
[liz@techpulp ~]# pwd /home/neo/demo/dir1 [liz@techpulp ~]# [liz@techpulp ~]# cd ../dir2 [liz@techpulp ~]# pwd /home/neo/demo/dir2 [liz@techpulp ~]# cd - /home/neo/demo/dir1 [liz@techpulp ~]# pwd /home/neo/demo/dir1 [liz@techpulp ~]# cd - /home/neo/demo/dir2 [liz@techpulp ~]# pwd /home/neo/demo/dir2 [liz@techpulp ~]#


about 3 years ago
A wonderful article…. this is just what I needed to read today. Thanks for describing the way you work.
about 6 months ago
Great, a time-saver! It’s strange that under Ubuntu there is no manual entry for these two commands…