2015/03/13

Ways to navigate directories in Linux

Generally speaking, there are 2 types of commands for navigating directories in Linux system.
They are listed in the following.
  • cd
  • pushd and popd

cd

$> cd <PATH>
Besides jumping to <PATH>, command cd will also remember the last directory you have visited. It means that you can jump back and forth between the current location and the previous location.
# For demonstration, assuming we are staying at dir1 first
$ ~/dir1>

# Go to dir2 
$ ~/dir1> cd ../dir2

$ ~/dir2> 

# Jump back to dir1
$ ~/dir2> cd -

$ ~/dir1>

# Jump back to dir2
$ ~/dir1> cd -

$ ~/dir2>  

pushd and popd

Since command cd is able to remember only one directory, you need to use pushd and popd if you would records more.
# Assume we are staying at dir1
$ ~/dir1>

# Go to directory dir2 and records down
# NOTE:
# There are 2 records. The left one represents current directory while the right 
# one represents the directory you have pushed.
$ ~/dir1> pushd ../dir2
~/dir2 ~/dir1

$ ~/dir2>

# Go to directory dir3 and records down
$ ~/dir2> pushd ../dir3
~/dir3 ~/dir2 ~/dir1

$ ~/dir3>

# Checkout current directory stack
$ ~/dir3> dirs
~/dir3 ~/dir2 ~/dir1

# Go back dir2
$ ~/dir3> popd

$ ~/dir2>

# Go back dir1
$ ~/dir2> popd

$ ~/dir1>

# Errors
$ ~/dir1> popd
bash: popd: directory stack empty

沒有留言:

張貼留言