You often create new directories and immediately change into them for some operation, and all that typing is tedious.
Add the following function to an appropriate configuration file such as your ~/.bashrc file and source it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# 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:
1 2 3 4 5 6 7 8 9 10 11 12 |
$ source mcd $ pwd /home/jp $ mcd 0700 junk $ pwd /home/jp/junk $ ls -ld . drwx------ 2 jp users 512 Dec 6 01:03 . |
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 lying around:
1 2 3 |
$ mcd /etc/junk mkdir: /etc/junk: Permission denied -bash: cd: _mcd_command_failed_: No such file or directory |
You might think that we could easily improve this using break or exit if the mkdir fails. break only works in a for, while, or until loop and exit will actually exit our shell, since a sourced function runs in the same process as the shell.
We could, however, use return, which we will leave as an exercise for the reader.
1 2 |
command mkdir -p "$1" && newdir="$1" || exit 1 # This will exit our shell command mkdir -p "$1" && newdir="$1" || break # This will fail |
You could also place the following in a trivial function, but we obviously prefer the more robust version given in the solution:
1 |
function mcd { mkdir "$1" && cd "$1"; } |
BASH – 2 list files, change directory, and navigation