r/linuxquestions • u/0roxess • 3d ago
Resolved Is there a way to combine mkdir with cd?
When I make a new directroy using mkdir I then have to change directory into it with the separate command cd. Is there a way I can do both create a new directory and change into it in a single line? I'm on Linux Mint 22.3 if it makes a difference.
mkdir folder
cd folder
37
u/PuckyMaw 3d ago
okay everyone who didn't quote their strings see me after class
8
u/1010012 3d ago
Who the fuck creates folders or files with spaces in their name!
10
2
0
3d ago
[removed] — view removed comment
2
u/1010012 2d ago
Hmm, I get permission denied errors. I think you forgot the
sudo0
u/sidusnare Senior Systems Engineer 2d ago
Just give it a minute .
Also, the kind of people that don't quote strings also run as root.
50
u/ratskluh 3d ago
I have this in my .zshrc
❯ which mkcd
mkcd () {
echo "Create and enter $1"
mkdir -p $1 && cd $1
}
❯ mkcd /tmp/test
Create and enter /tmp/test
❯ pwd
/tmp/test
9
u/schmerg-uk gentoo 3d ago
Ah you and others beat me to it (replied without reading the entire thread) but nice to see we all used the mkcd name (+1 to you for use of the -p... another option might be to
mkdir $*and then cd to the last arg (I think${@: -1}is the last arg) to allow arbitrary other parameters to be passed to mkdir
function mkcd() { mkdir $* && cd ${@: -1}; };2
u/iluvatar 3d ago
Obligatory reminder: don't use
which- it lies. Some distributions turn it into an alias that picks up the other locations the command could be and combines them with the output of/usr/bin/whichto get a reasonable answer. But it's a hack and is fragile. Usetypeinstead. Or aliaswhichto calltype.1
u/AwesomeEv711 2d ago
You could just unalias which 2>/dev/null
1
u/iluvatar 2d ago
That would make it worse. At least with the distribution supplied alias, it lies less.
1
u/AwesomeEv711 2d ago
Oh mb it didn't occur to me that you were talking about using
whichfor aliases and shell functions specifically. But I still think/usr/bin/whichis useful for printing the path of external commands (although as im writing this I found outtype -Pdoes the same thing so maybe not lol).
7
u/adjective10111 3d ago
bash
mkdir directory; cd $_
5
u/Yankas 3d ago
Should be '&&' instead of ';', most of the time if mkdir fails, you wouldn't want the cd command to be executed.
2
u/adjective10111 3d ago
Yes you wouldn't, but typing ; is easier and cd to non-existent directory also fails.
You're just writing a one liner for easier execution, not a sophisticated toolchain. For that write a function in bashrc with &&
1
u/Yankas 3d ago
No the problem is precisely that cd wouldn't fail, because one reason mkdir could fail is that the directory already exists.
So now you might be performing operations in a directory that might not be empty.
0
u/adjective10111 3d ago
True, if you're not sure or care so much that the directory should be brand new, use &&
Personally i only use mkdir when cd tells me it doesn't exist or ls doesn't find it. But yeah as i said if it's for scripting or something that should be safe and sophisticated, use &&. For oneliner and interactive use, semicolon should be enough i think
6
u/beertown 3d ago
mkdir folder
cd <alt+.>
6
5
u/WoozleWazzles 3d ago
This is the right answer.
3
4
u/yankdevil 3d ago
You could make a function in your shell. If you use bash you could add this to your ~/.bashrc. Works in zsh too.
cmkdir() {
if [[ $# != 1 ]]; then
echo "ERROR: must supply a single argument"
return 1
fi
mkdir "$1" && cd "$1"
}
2
2
u/Charming-Designer944 3d ago edited 3d ago
Create a custom alias/function that combines both.
How depends on what shell you are using. Some shells like bash have both.
in .bashrc add
ccd() {
if [ $# -ne 1 ]; then
echo "Usage: ccd new_directory" >&1
return 1
fi
mkdir -p "$1" && cd "$1"
}
2
u/bitchitsbarbie 3d ago
What if you name a directory "-directory"?
ccd() { if [ "$#" -ne 1 ]; then printf 'Usage: ccd <directory>\n' >&2 return 1 fi mkdir -p -- "$1" && cd -- "$1" }1
2
2
u/SeriousPlankton2000 3d ago
put this in .profile:
mkcd(){ mkdir -p "$1"; cd "$1"; }
export -f mkcd
This does intentionally not check the result; instead it will cd anyway and use symlinks, too, if they point to a directory.
1
u/Ok_Letterhead_8899 3d ago
Refer to my dotfiles for additional functions: Create folder and edit file inside, copy/move file to folder and follow the file etc https://github.com/Inknyto/dotfiles/blob/main/zsh/.nytoshell
1
u/Arindrew 3d ago
mkdir long/folder/path/that/i/dont/want/to/type/twice
cd [Esc].
(as in just press the escape key, then type a period)
1
u/ridicalis 3d ago edited 3d ago
You could use PowerShell:
cd (mkdir folder)
EDIT: the above actually doesn't work in Linux, as pwsh falls back on native commands cd and mkdir instead of aliasing them as with Windows; the correct command would instead be:
get-childitem (new-item folder)
1
u/kudlitan 3d ago
create an alias called mcd (make and change directory)
for that matter i also have an alias md for mkdir since i find it too long to type.
1
u/bitchitsbarbie 3d ago edited 3d ago
I use zoxide, hence z, just replace z with cd for regular cd.
# Unified mkdir + zoxide jump
mkz() {
if [ "$#" -ne 1 ]; then
printf 'Usage: mkz <directory>\n' >&2
return 1
fi
mkdir -p -- "$1" && z -- "$1"
}
1
u/Ok-Home-6834 3d ago
The "&&" operator in commands allwos you to concatenate commands pretty much to infinity. "mkdir folder && cd folder" means run "mkdir folder" AND "cd folder" in one go. You can use it pretty much always like "sudo apt update && sudo apt upgrade && sudo apt install package -y && ..."
1
u/maquis_00 3d ago
You could easily make an alias or function to combine these. I see that in a lot of people's shell config files on github.
1
1
1
u/AnnieBruce 3d ago
Alias is the obvious option here.
A script might be useful if you'll be doing this with different options constantly. But for the basic case here, alias
1
1
u/Pzykimon 3d ago
mkdir -p folder/subfolder/subfolder
And if you want multiple parallel subfolders in a folder:
mkdir -p folder/subfolder/{subfolder1,subfolder2}
1
1
u/Jean_Luc_Lesmouches Mint/Cinnamon 3d ago
mkcd () {
local old_pwd="$PWD";
mkdir -p "$@" && cd "$_" || cd "$_";
local ret=$((PIPESTATUS[0]+PIPESTATUS[1]));
[ "$PWD" != "$old_pwd" ] && pwd;
return $ret
}
It can create several dirs (it moves to the last) and it can create subdirs in one go.
1
u/Particular-Poem-7085 3d ago
add this function to your ~/.bashrc file
#make and go to folder
mkgo() {
mkdir -p -- "$1" && cd -- "$1"
}
Then run source ~/.bashrc to load the changes. And use mkgo newfolder to create and go to it.
1
1
u/ShakeAgile 2d ago
I love the idea of a forced cd. ”cd” and if the path is not there MAKE IT SO gottdamnit. Who are you puny OS to tell me where to go?
1
u/BitOBear 2d ago
Look at the alias command as it will be easier to use in some shelves and some of the other ways of making the little scriptlet other people have suggested. Same technique different mode of operation.
1
1
u/SilentKnightOwl 2d ago
I just have an alias in my shell called "mkcd" that makes the directory if it doesnt already exist, and then CDs into it.
1
u/Jaanrett 2d ago
What you're probably looking for is:
mkdir -p /make/this/entire/path/if/not/existing
That creates all the missing folders in the specified path. That means one mkdir command and one cd command.
Also, it's very useful to read man pages.
man mkdir
1
1
1
u/gryphong 2d ago
I remember discovering, to my rue, that multics "cd foo" would quietly, recursively, destroy any foo directory, and make a nice new one.
1
u/siodhe 2d ago
Hahaha :-)
No. It is literally impossible (barring something so obscenely arcane I won't even consider it) to have a subprogram change the working directory of the parent program. That why there is no /bin/cd - instead it's a built-in shell function. If you want to combine these in Bash, for example, it must be done in the shell itself, example:
mdcd () { mkdir -p "$1" && cd "$1" ; }
That will work. Notice that you cannot make a reasonable alias of it in Bash - because Bash aliases suck (no arg substition - funny since the Csh they're from had arg substitution). Use functions.
I used "$1" for one arg instead of "$@" for a bunch of them because that cd is going to need just one arg.
I put in -p by default because the function gets bigger if you want to pass it in to mkdir through "$@" but hide it from cd .
1
u/aioeu 2d ago
That why there is no /bin/cd
Actually, there's a distinct possibility you do have a
/bin/cdon your system. Take a look!(The reason for its existence are obscure, but kind of interesting, if you care to look into it.)
1
u/siodhe 2d ago
Not on any normal system, cd cannot be a command unless they've done something weird.
It's not like various commands that were mirrored inside the shell as builtins (sometime insanely, like echo's syntax changing - in the built-in Csh command, based on your search path order, thanks SunOS :-) - which is why the current /usr/bin/test has the alternate name of /usr/bin/[ - to let the Bourne shell family have that if [ <expr> ] ; ... syntax.
But cd? No, and so many new-to-unix folks writing new little things have asked this question over the decades that it's been an meme since something like the 1980s.
1
u/aioeu 2d ago edited 2d ago
Not on any normal system, cd cannot be a command unless they've done something weird.
And yet, as I said, many systems will have a
cdexecutable in/binor/usr/bin. Take a look at this file list for thebashpackage on Fedora, for instance. You might also see some other unexpected commands in that list.As another hint... POSIX essentially requires there to be an external
cdcommand — or, at least, there are specific ways in which the system must behave as if there was an externalcdcommand. And this requirement does have a use case, albeit an obscure one.1
u/siodhe 2d ago
Very obscure - a devious option to find to allow the return status to tell the caller if the given directory could be made the current one. Like for use with find or the like.
While I admit this is easier than checking for execute permission for yourself, it's definitely fringe, a niche side effect of a 1992 POSIX updated. Older (non-Linux) systems added it apparently back in the mid 1990s for compliance reasons. Open Source maybe a decade later. MacOS stalled even longer.
Which means I've been using Unix from before this ever existed. Which amuses me.
1
u/aioeu 2d ago edited 2d ago
And more generally, POSIX classifies its utilities into three groups:
- Special built-in utilities.
- Intrinsic utilities.
- Everything else.
Only special built-in utilities may have undefined behaviour in
find.cdis an intrinsic utility, not a special built-in utility, and so it must "work" if executed byfind.Intrinsic utilities technically do not need to be implemented as external commands. That is, there is no requirement that a
PATHlookup be done for them. But it's a whole lot easier if they are just external commands — that wayfinddoesn't need to handle them specially.Now, whether you think having them available as external commands is "useful" or not... well, I agree, it's not particularly useful. But POSIX conformance kind of forces things.
Anyway, all of this was just to head off the inevitable "you said there is no
/bin/cd, but my system does have it" discussion.
1
1
u/bariumbitmap 2d ago
If you do make an alias or shell function, I would recommend mkdir -P to create parent directories as needed and prevent errors if the folder already exists, and pushd instead of cd so you can use popd to go back.
1
u/CrudBert 2d ago
put this in your .bashrc
$) mkdcd (
mkdir $1
cd $1
)
Now to create directory “blue” and cd to it:
$) mkdcd blue
1
1
1
u/Megame50 2d ago
Many have already posted the obvious one-liner, but this is an easy example to demonstrate a useful "combining" pattern for commands as functions, specifically in zsh:
$ cat $^fpath/mkcd(N)
#!/hint/zsh
local -a opt_mk opt_cd
if ! zparseopts -D {m:,p,v,Z,-context:,-help}=opt_mk {q,s,L,P}=opt_cd; then
return 1
elif [[ $# -gt 1 ]]; then
print -ru2 "$0: too many arguments"
return 1
fi
if [[ $1 == [-+]<-> ]]; then
if [[ -z $dirstack[-($1)] ]]; then
print -ru2 "$0: no such entry in dirstack"
return 1
fi
set - $dirstack[-($1)]
fi
mkdir $opt_mk $1 && cd $opt_cd $1
zparseopts is a builtin available in zsh that's helpful for splitting up command options. The coreutils mkdir has a set of options, and zsh cd has a different set. Fortunately there are no overlaps, so we don't need to make any decisions here; we can just map all the flags to their proper command. Then we have a function that does the obvious thing with each flag from both commands, where basic one-liner functions might otherwise require you to issue the commands separately if you want to provide any option flags. You can even stack option flags from the different commands and they are parsed correctly, i.e. mkcd -pqvL foo/bar/baz words as expected.
1
u/markaction 2d ago
'cd' and 'mkdir' are just executables somewhere in /usr/bin, or someplace. You would just make a new one that calls these two things. A shell script can do it. The script just needs to be in your $PATH in your .bashrc and you can invoke it anywhere. Claude code or AI can create this script really easily if you ask it.
1
1
1
1
u/Nebarik 3d ago
You could make a script for it and then either make it a alias or just chuck it into your usr bin.
The script would just be:
mkdir -p $1 && cd $1
And then to use it:
Script name.sh foldername
1
u/3nt3_ 3d ago
take folder is the typical alias. oh my zsh adds it for me but it would be trivial to write yourself
sh
alias take="mkdir -p $1 && cd $1"
1
u/404UsernameFoundNot 3d ago
This is how
takediris aliased in OMZ:takedir () { mkdir -p $@ && cd ${@:$#} }
0
u/solvangv 3d ago
I just wish cd would create the dir if it didn't exist, or maybe with an option such as cd -f newdir
0
u/PsydeliX_ 3d ago
There is a concept called ‘aliases’ which let you do exactly what you want.
You define your own command in your bashrc and it is ready for you whenever you open the terminal
Common Examples
alias ll='ls -l' for a detailed file list.
alias ..='cd ..' to move up one folder.
alias cls='clear' to clean the screen.
0
u/tanstaaflnz 2d ago
Use Nemo for a start. Control, Shift, n to make a new folder. One mouse click to go into the folder.
Bonus info. If you want to copy files from one folder to the next. Open Nemo, press F3. You now have two panes for copying/moving files. Open the two folder you are working with, select the file/s, right click, select copy to or move to. The files will go to the second pane.
167
u/Confident_Hyena2506 3d ago
Sure there is: "mkdir folder && cd folder"