How to mkdir and switch to new directory in one li

2020-03-24 05:57发布

I have been using the linux console for some time now. One thing that irritates me is that every time I create a new directory using mkdir I have to cd to change to it. Is there a single command solution to create and switch to the directory just created?

Right now I do:

mkdir php5
cd php5

can I do:

mkdir -someswitch php5

I want something simple and clean. A good example is git branch somebranch which makes new branch and git checkout -b somebranch which makes and switches to new branch.

5条回答
再贱就再见
2楼-- · 2020-03-24 06:31

A close answer that can help. It is easy to type.

 mkdir php7 && cd !$ 
查看更多
家丑人穷心不美
3楼-- · 2020-03-24 06:37

The portable way to do this is with a shell function--not a bash function (using bashims like function). Put this in the relevant .profile for interactive use:

 mkdir () {
    case $1 in
       (-c) command mkdir -p "$2" && cd "$2";;
       (*)  command mkdir "$@";;
    esac
 }

This adds the -c option to mkdir for interactive use. Without -c the utility acts as it always does.- And note the quoting of "$2" so this works with directories with white space in their name.

查看更多
欢心
4楼-- · 2020-03-24 06:39

nothing prevents you from creating your own alias or small script

mkdir $1 && cd $1
查看更多
狗以群分
5楼-- · 2020-03-24 06:41

Or you can use ';' to separate commands, like:

mkdir php5.3 ; cd php5.3

查看更多
Evening l夕情丶
6楼-- · 2020-03-24 06:41

You can define a function in bash to do this:

function mkcd() {
    mkdir $1 && eval cd $1
}
查看更多
登录 后发表回答