Hack 3. Perform mkdir and cd using a single command

by Ramesh

Sometimes when you create a new directory, you may cd to the new directory immediately to perform some work as shown below.

  1. # mkdir -p /tmp/subdir1/subdir2/subdir3
  2.  
  3. # cd /tmp/subdir1/subdir2/subdir3
  4.  
  5. # pwd
  6. /tmp/subdir1/subdir2/subdir3

Wouldn’t it be nice to combine both mkdir and cd in a single command? Add the following to the .bash_profile and re-login.

  1. $ vi .bash_profile
  2.  
  3. function mkdircd () { mkdir -p "$@" && eval cd "\"\$$#\""; }
  4.  
  5. Now, perform both mkdir and cd at the same time using a single command as shown below:
  6.  
  7. # mkdircd /tmp/subdir1/subdir2/subdir3
  8.  
  9. [Note: This creates the directory and cd to it automatically]
  10.  
  11. # pwd
  12. /tmp/subdir1/subdir2/subdir3