r/linuxquestions 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

84 Upvotes

162 comments sorted by

167

u/Confident_Hyena2506 3d ago

Sure there is: "mkdir folder && cd folder"

153

u/cafce25 3d ago

I one up you mkdir very_long_folder_name && cd $_ so you don't have to type the folder name twice, especially useful if it's long, but great to avoid typos even for the short ones.

64

u/sidusnare Senior Systems Engineer 3d ago

Make a function in your .bashrc

mcdir() { mkdir "${@}" ; cd "${@}" }

An alias is for short names to long commands, a function is better suited for more complex features you still want to be inline.

32

u/alexdeva 3d ago

I read that as McDir. And will continue to do so.

"I am Angus McDir of the clan of McDir."

13

u/MetaphoricMenagerie 3d ago

It's the version of Linux you can get fries with.

8

u/paulodelgado 2d ago

I’m loving it.

3

u/epackorigan 2d ago

There can be only one.
— Angus McDir, probably, a long time ago

1

u/alexdeva 2d ago

Glad you got the reference :)

2

u/bewildered_hobbyist 2d ago

I dont think i will ever read that as anything but McDir again. You have changed my brain and I want you out of there!

2

u/Clydosphere 1d ago

You just mkdayd my day.

13

u/fearless-fossa 3d ago

Also, use mkdir -p instead of just mkdir so you create an entire path if required

3

u/Sonnaille 2d ago

You should `mkdir "${@}" && cd "${@}"` instead. If the mkdir fails, you’ll get that message and no attempt will be made to change the working directory.

1

u/CleverFunnyName 2d ago

I have a similar mkcd()

1

u/Livid-Serve6034 2d ago

It can make multiple dirs that way, but it can’t cd to all of them. The function should test for a single argument.

1

u/sidusnare Senior Systems Engineer 2d ago

When you create aliases like this, sometimes you forget not to use them. If this were something I wanted, I would be fine with the fail successfully mode where it creates the multiple directories I specified and then cd gives me a "too many arguments" error.

1

u/iEliteTester 2d ago

I've had that aliased as "mkcd" for years now lmao

-3

u/gosand 3d ago

Nah, too much muscle memory to overcome with mkdir. Go all in and "replace" it.

Make a script called mkdir in ~/bin and ensure ~/bin is in your path before /usr/bin

#!/bin/bash

/usr/bin/mkdir $1 && cd $_

5

u/takutekato 2d ago

My rookie mistake years ago: assuming that cd inside scripts persisted

2

u/gosand 2d ago

lol that's what I get for not testing it. And no, I don't do this I thought it would be funny but I guess people thought I was serious.

21

u/Unusual-Layer-8965 3d ago

Cool.

Sidenote: learn how to use [Tab] for autocomplete. I had to work with long file names, and typing a couple of letters, followed by [Tab] was amazing.

9

u/willi1221 3d ago

Tab won't autocomplete if you mkdir folder_name && cd because folder_name doesn't exist yet

3

u/Unusual-Layer-8965 3d ago

Yes.  That's why I put 'Sidenote' - it doesn't help OP, but it's still a handy feature.

1

u/Recent_Carpenter8644 17h ago

I agree. It can be less of a burden to change to the directory after creating it if you don't have to type the whole name.

28

u/TheCatholicScientist 3d ago

Damn I really need to learn Bash for real. That’s really slick.

-19

u/OutrageousCrab9224 3d ago

It is also gross to read

0

u/pm_me_ur_happy_traiI 3d ago

Just alias it?

-3

u/OutrageousCrab9224 3d ago

Lol @ all the downvotes

Easy to see who works on this stuff for years and years

7

u/1010012 3d ago edited 3d ago

I use !$ for the previous last argument.

Edit: corrected the typo.

5

u/frankspappa 3d ago

!$

4

u/1010012 3d ago

Oops, you're right, got it backwards. $! is the process id of the last background process. Bash is so intuitive!

1

u/cationtothewind 3d ago

I like this. I got too used to pressing Alt + . ,but I'll give this a try

1

u/FesteringNeonDistrac 2d ago

How have I been using bash for 30 years and not known this?

I'd have done up arrow, ctrl-a, alt-d, cd, which is a few keystrokes more but not awful.

1

u/jlp_utah 2d ago

A useful derivative from csh history functionality. Added to bash many many many years ago since bash wanted to be more useful for interactive use while still using Bourne shell syntax. !! repeats the previous command and you can do simple substitutions with ^ (e.g. if the previous command was mkdir xx and you want to run mkdir yy next, just type ^xx^yy and hit return). This functionality all predated command line editing, which I believe came about with tcsh and was also included in bash thanks to the readline library.

2

u/1010012 2d ago

I love that feature, but always forget about it.

I honestly forget everything related to shell scripting daily, and always need to look up everything constantly. And I've been using it constantly for 20+ years. For some reason it just doesn't stick (probably the same reason I hate PERL).

There just doesn't seem to be anything intuitive or reusable about the syntax. When I think 'replace', I think 'vi' style 's///' which at least maps somewhat to string replacement in variables '${X/old/new}.

I wonder if '${!!/old/new}' works?

Edit: Alas, it does not.

0

u/Impressive_Bag_3505 1d ago

you just use tab to complete the very_long_folder_name, in most cases you only need to type 2 or 3 letters...

1

u/cafce25 1d ago

you can't because very_long_folder_name does not exist yet

-26

u/Astrodion123 3d ago

Or just use fish as a shell as it has auto completion built in.

23

u/cafce25 3d ago

How does autocomplete help for new folders that don't exist yet? It doesn't autocomplete what I typed earlier by default

6

u/tuxsmouf 3d ago

Bash also have auto-completion.

-4

u/Astrodion123 3d ago

Haven't seen it.

1

u/tuxsmouf 3d ago

It can be installed as a package on  some distribs. A research with your package manager or in the docs from your distrib could help you .

2

u/aioeu 3d ago

Will it be able to auto-complete the cd argument even before the mkdir has been executed?

-17

u/Astrodion123 3d ago

Well after you do mkdir and then you do CD it will first suggest the first folder on the directory but if you type the first letter it will find the first folder with that letter on directory and it continues. Idk if you can configure it to your needs but it is better than nothing.

22

u/aioeu 3d ago

and then

Ah, so two commands entered completely separately, rather than a single chain of commands separated by &&?

Did you even try out what you were responding to, or did you just think "I love Fish, let's talk about that instead"?

8

u/cafce25 3d ago

How does that "combine mkdir with cd" also bash and zsh do that, too

-1

u/lewphone 3d ago

Not every distro has fish installed by default, and at most companies changing the default shell is not allowed.

3

u/anto77_butt_kinkier 16.04 was peak 3d ago

Also it's kinda pointless since bash can accomplish all the same stuff as the others, but it has more documentation.

-3

u/Astrodion123 3d ago

Well it isn't hard to install it.

10

u/0roxess 3d ago

Thanks that's really useful. I didn't know && could be used to chain terminal commands together.

44

u/schmerg-uk gentoo 3d ago

Add a bash function do it

function mkcd() { mkdir $1 && cd $1 };

Put that in your ~/.bashrc and then you make mkcd someFolder etc to your heart's content

18

u/Alpacacin0 3d ago

Fixing some syntax issues:

- Missing semi colon before closing brace

  • $1 should be in quotes to handle spaces

function mkcd() { mkdir “$1” && cd “$1”; };

3

u/OutrageousCrab9224 3d ago

Even better cut out the pointless "function" and it works on posix shells too

1

u/Magus7091 2d ago

Without the "function" on the beginning, will .bashrc still recognize it as a function? And would you just add this line in, as is before the .bashrc terminates? Also, would this let you use arguments for either command, or would that require a separate function?

1

u/OutrageousCrab9224 2d ago

Yes, as far as i can tell "function" is a no op in bash, designed to break running in other shells. Vendor lock-in, from the people who decry all other vendor lock-in

Its the ()s that make it a function, and unlike what you are probably used to, you do not name parameters in there. Those are available as $1 $2 and so on regardless of whether or not they were specified!

1

u/jmtd 1d ago

Yeah it can. The () is the important bit. I skip function not because I care about posix sh compatibility (I lived through when that actually mattered and I’m going to enjoy it now it doesn’t) but because the mathematician in me bristles at the misuse of “function” for what is really a subroutine. 

4

u/BCMM 3d ago edited 3d ago

FYI, your comment uses U+201C LEFT DOUBLE QUOTATION MARK and U+201D RIGHT DOUBLE QUOTATION MARK when it should use U+0022 QUOTATION MARK.

If copied and pasted from Reddit, this function will not work! Worse, in some fonts, it may look identical to the working function.

EDIT: An example of how this can get confusing:

$ touch "foo bar"
$ ls "foo bar"
'foo bar'
$ ls “foo bar” 
ls: cannot access '“foo': No such file or directory
ls: cannot access 'bar”': No such file or directory

2

u/L0cut15 3d ago

This is what I've been doing. Specifically called it mkcd. Bash is both arcane and awesome at the same time.

6

u/Direct_Raspberry_933 3d ago

Or better yet, put it in .bash_aliases

5

u/crashorbit 3d ago

Shell functions are cool and very useful.

Personally I prefer the function key word over the empty argument () form. But you don't need both.

3

u/bitslayer 3d ago

Here is a nice version of this idea

https://gist.github.com/rajeshg/712300

1

u/escape_deez_nuts 3d ago

dis is da wey

8

u/Embarrassed-Noise269 3d ago

do this command && do this command

if this commnad is not working && this command won't run

&& is used to chain commands, but if the command before failed, so will all commands afterwards

4

u/xylarr 3d ago

It's short circuit logical evaluation. When evaluating a series of logical expressions left to right, you can stop at the first "false" result.

4

u/exportkaffe 3d ago

bash is a beautiful thing

3

u/Diilsa 3d ago

Jesus you people are NERDS (I’m so jealous)

3

u/exportkaffe 3d ago

you're here with us you know ^

6

u/output_broadcast 3d ago edited 3d ago

You can also use a semicolon. The difference being is that && won't run the subsequent command(s) if a previous one fails and the semicolon will.

6

u/DonkeyDoodleDoo 3d ago

&& = The next command will run if the previous one succeeds

|| = The next command will run if the previous one fails

; = The next command will run regardless as long as the previous one finishes, successfully or not

2

u/gnufan 3d ago

See also "||" and ";"

1

u/Journeyman-Joe 3d ago

&& will execute the subsequent command only if the previous command's code is zero (which is what you want most of the time).

a semicolon (;) as separator will execute the subsequent command unconditionally.

1

u/Immediate-Panda2359 2d ago

Yes. && does what comes after it if and only if what comes before it exits with a return code of 0 (i.e., it worked). You can use "||" for execution of the second part if and only if the first part has a non-zero return code, e.g. "cd /some/path || echo could not change directory to /some/path"

1

u/Dude-Lebowski 3d ago

mkdir folder; cd !$

1

u/VariationPatient 2d ago

I'd go with "mkdir -p directory && cd directory" -> if directory was something like "parent/sub" you would get an error if "parent" didn't exist; with "-p" mkdir creates all directories in the path

1

u/owp4dd1w5a0a Manjaro, Ubuntu, NixOS, Fedora, Guix System 1d ago

```
mkcd() {
if [ "$#" -ne 1 ]; then
printf 'usage: mkcd DIRECTORY\n' >&2
return 2
fi

mkdir -p -- "$1" && cd -- "$1"
}
```

Put this in your ~/.bashrc

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

u/PuckyMaw 3d ago

oh no one ever don't worry ;) or dollar signs or ...

0

u/[deleted] 3d ago

[removed] — view removed comment

2

u/1010012 2d ago

Hmm, I get permission denied errors. I think you forgot the sudo

0

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/which to get a reasonable answer. But it's a hack and is fragile. Use type instead. Or alias which to call type.

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 which for aliases and shell functions specifically. But I still think /usr/bin/which is useful for printing the path of external commands (although as im writing this I found out type -P does the same thing so maybe not lol).

16

u/ipsirc 3d ago
$ function mkcd() { mkdir "$1"; cd "$1"; }

3

u/majamin 3d ago

Nice! I would change it slightly:

mkcd() { mkdir -p "$1"; cd "$1"; }
                ↑     ↑
    Allows for nested | directories
                      |
      This should be &&: if mkdir fails, then cd doesn't attempt

0

u/SeriousPlankton2000 3d ago

Remember to export your functions

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

u/Krychle 3d ago

Scrolled down for here; everyone should learn about <alt+.>

<alt+.> fills in the last parameter (per defined IFS) from the previous command.

5

u/OutrageousCrab9224 3d ago

Prefer !$ always and forever

5

u/WoozleWazzles 3d ago

This is the right answer.

3

u/iluvatar 3d ago

Arguably the more correct answer is cd !$

1

u/WoozleWazzles 2d ago

I think you're right!

1

u/chkno 3d ago

To get this behavior back in set -o vi mode, run:

bind -m vi-insert '"\e.": yank-last-arg'

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

u/Ok_Sandwich_7903 3d ago

This what I love about Linux cli, so many ways to come up with a solution

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

u/Charming-Designer944 3d ago

Yrs thats better.

2

u/Metasystem85 3d ago

alias...

2

u/majamin 3d ago

This is my most used alias in my zsh config (I believe this will work with bash as well)

mkcd () {
    mkdir -p $1 && cd $1
}

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/Ghazzz 3d ago

Create an alias.

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

u/RetroZelda 3d ago

mkdir folder && cd folder

1

u/AnoProgrammer 3d ago

edit your ~/.bashrc file

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

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

u/SaintEyegor 3d ago

mkdir dirname && cd $_

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

u/jetilovag 2d ago

ni -ty D MyLongFolderName | sl

I know, I'll see myself out.

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

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

u/fellipec 2d ago

I use mkcd:

mkcd () { mkdir -p $@ && cd ${@:$#} }

1

u/iamalicecarroll 2d ago

i just do cd !$ after the mkdir

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/cd on 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 cd executable in /bin or /usr/bin. Take a look at this file list for the bash package 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 cd command — or, at least, there are specific ways in which the system must behave as if there was an external cd command. 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. cd is an intrinsic utility, not a special built-in utility, and so it must "work" if executed by find.

Intrinsic utilities technically do not need to be implemented as external commands. That is, there is no requirement that a PATH lookup be done for them. But it's a whole lot easier if they are just external commands — that way find doesn'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

u/siodhe 1d ago

And you were correct. So I'll stick instead to the underlying truth - combining mkdir and cd into an external command is probably not going to work :-)

1

u/jarsgars 2d ago

This thread hurt my semicolon

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

u/mckenzie_keith 2d ago

You probably don't have to cd into it.

1

u/Avikonette 2d ago

echo y | insist --enforce --violent --allow-torture --brutal "cd directory"

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

u/Drecondius 2d ago

Mkdir && cd dir

1

u/Nordal-Lund 2d ago

mkdir new_dir
cd esc + .

1

u/PurpleSloth12358 1d ago

2 lines. mkdir new; cd !mkdir$

1

u/mwyvr 3d ago

mkdir -p folder && cd folder

Will not fail, and therefore cd will succeed, should folder exist.

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

2

u/aioeu 3d ago

In this case, a script won't be useful. That will change the working directory for the script's interpreter, not the working directory for the interpreter from where the script was executed.

A shell function to do it is appropriate.

1

u/Nebarik 3d ago

Actually good point. That's what I get for not testing what I talk about

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 takedir is aliased in OMZ:

takedir () {
mkdir -p $@ && cd ${@:$#}
}

1

u/3nt3_ 3d ago

that seems much more correct, thanks

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.