Creating and Changing into a New Directory in One Step
Problem
You often create new directories and immediately change into them for some operation, and all that typing is tedious.
Solution
Add the following function to an appropriate configuration file such as your ~/.bashrc file and source it:
# cookbook filename: func_mcd # mkdir newdir then cd into it # usage: mcd (<mode>) <dir> function mcd { local newdir='_mcd_command_failed_' if [ -d "$1" ]; then # Dir exists, mention that... echo "$1 exists..." newdir="$1" else if [ -n "$2" ]; then # We've specified a mode command mkdir -p -m $1 "$2" && newdir="$2" else # Plain old mkdir command mkdir -p "$1" && newdir="$1" fi fi builtin cd "$newdir" # No matter what, cd into it } # end of mcd
For example:
$ source mcd $ pwd /home/jp $ mcd 0700 junk $ pwd /home/jp/junk $ ls -ld . drwx------ 2 jp users 512 Dec 6 01:03 .
Discussion
This function allows you to optionally specify a mode for the mkdir command to use when creating the directory. If the directory already exists, it will mention that fact but still cd into it. We use the command command to make sure that we ignore any shell functions for mkdir, and the builtin command to make sure we only use the shell cd.
We also assign _mcd_command_failed_
to a local variable in
case the mkdir fails. If it works, the correct new
directory is assigned. If it fails, when the cd
tries to execute it will display a reasonably useful message, assuming
you don’t have a lot of _mcd_ command_failed_ directories ...
Get bash Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.