0

Quick question:

Is it possible to use "mkdir" to make a new directory AND change to that directory at the same time using a single 'mkdir' command?

Whole question:

I have this question:

What single Linux “mkdir” command could replace the sequence of commands?
         mkdir a
         cd a
         mkdir b
         cd b
         mkdir c
         cd ../..

My answer is:

         mkdir a b c && cd c

Is there a single "mkdir" command, without using any other commands, perhaps with some flags or something, I can use to make AND change directory at the same time?

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
Matt
  • 375
  • 1
  • 5
  • 10

2 Answers2

2

The question you present of using a single mkdir command to do the same as the other steps doesn't really involve changing directories. It ends with cd ../.. which brings you back to the directory you were in at the start.

In effect, that sequence of commands creates a directory a, then a directory b within it (in other words, a/b), then a directory c within the just created b (in other words, a/b/c.)

You can do the same with a single mkdir command that creates the nested directories after creating their parents:

mkdir a a/b a/b/c

Another way is using mkdir's -p option, which will create the parent directories if necessary, so you don't need to specify them:

mkdir -p a/b/c

This doesn't answer your question in the title (for mkdir + cd look at the duplicates from the comments), but addresses the question in your text, about the equivalent single mkdir command for that sequence, in which at the end of the sequence the directory is the same as at the start of it.

filbranden
  • 21,751
  • 4
  • 63
  • 86
1

Do it as a function:

mkcdir ()
{
    mkdir -p -- "$1" &&
      cd -P -- "$1"
}