pushd and popd

Both pushd and popd are shell builtin commands. The pushd command is used to save the current directory into a stack and move to a new directory. Furthermore, popd can be used to return back to the previous directory that is on top of the stack.

It is very useful when we have to switch between two directories frequently.

The syntax of using pushd is as follows:

pushd [directory]

If no directory is specified, pushd changes the directory to whatever is on the top of the stack.

The syntax of using popd is as follows:

popd

Using the popd switch, we can go back to the previous directory that is on top of the stack and pop that directory from stack.

The following example counts the number of files or directories in a specified directory until one level:

#!/bin/bash
# Filename: pushd_popd.sh
# Description: Count number of files and directories

echo "Enter a directory path"
read path

if [ -d $path ]
then
   pushd $path > /dev/null
   echo "File count in $path directory = 'ls | wc -l'"
   for f in 'ls'
   do
      if [ -d $f ]
      then
         pushd $f > /dev/null
         echo "File count in sub-directory $f = 'ls | wc -l'"
         popd > /dev/null
      fi
   done
   popd > /dev/null
else
  echo "$path is not a directory"
fi

The output after running the preceding script is as follows:

Enter a directory path
/usr/local   
File count in /usr/local directory = 10
File count in sub-directory bin = 0
File count in sub-directory etc = 0
File count in sub-directory games = 0
File count in sub-directory include = 0
File count in sub-directory lib = 0
File count in sub-directory lib64 = 0
File count in sub-directory libexec = 0
File count in sub-directory sbin = 0
File count in sub-directory share = 3
File count in sub-directory src = 0
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.100.190