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 lying around:

$ 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.

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:

function mcd { mkdir "$1" && cd "$1"; }
..................Content has been hidden....................

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