Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One command to create and change directory

I'm searching for just one command — nothing with && or | — that creates a directory and then immediately changes your current directory to the newly-created directory. (This is a question someone got for his exams of "linux-usage", he made a new command that did that, but that didn't give him the points.) This is on a debian server if that matters.

like image 713
Autom3 Avatar asked Jan 03 '13 10:01

Autom3


People also ask

What is the command to create a directory?

Use the mkdir command to create one or more directories specified by the Directory parameter.

Which command is used to change directory?

The cd command, also known as chdir (change directory), is a command-line shell command used to change the current working directory in various operating systems. It can be used in shell scripts and batch files.

Does mkdir change directory?

How to Make a New Directory and Change to It with a Single Command in Linux. If you spend any time in the Terminal at all, you probably use the mkdir command to create a directory, and then the cd command to change to that directory right after.

How do I create a directory in command prompt?

To create a directory in MS-DOS or the Windows Command Prompt (cmd), use the md or mkdir MS-DOS command.


2 Answers

I believe you are looking for this:

mkdir project1 && cd "$_" 
like image 85
Marian Zburlea Avatar answered Sep 21 '22 00:09

Marian Zburlea


define a bash function for that purpose in your $HOME/.bashrc e.g.

 function mkdcd () {      mkdir "$1" && cd "$1"  } 

then type mkdcd foodir in your interactive shell

So stricto sensu, what you want to achieve is impossible without a shell function containing some && (or at least a ; ) ... In other words, the purpose of the exercise was to make you understand why functions (or aliases) are useful in a shell....

PS it should be a function, not a script (if it was a script, the cd would affect only the [sub-] shell running the script, not the interactive parent shell); it is impossible to make a single command or executable (not a shell function) which would change the directory of the invoking interactive parent shell (because each process has its own current directory, and you can only change the current directory of your own process, not of the invoking shell process).

PPS. In Posix shells you should remove the functionkeyword, and have the first line be mkdcd() {

like image 30
Basile Starynkevitch Avatar answered Sep 19 '22 00:09

Basile Starynkevitch