0

I've been trying do put together a function that combines mkdir and cd. This is what I've been using:

#!/bin/bash
mk(){
    mkdir "$1" && cd "$1"
}

mk $1

However, when I run the script using ./mker.sh test , it'll create a directory with but won't change into it. I'm brand new to Bash so I'm really at a loss as to why that part doesn't work. It doesn't return an error to the command line either.

What's the issue here? Thanks!

  • 1
    Scripts run in a subprocess, so `cd` changes the directory *of the subprocess*, not your shell. Use a function (directly, not in a script). This looks like a duplicate of ["Why I can't change directories using `cd`?"](https://stackoverflow.com/questions/255414/why-i-cant-change-directories-using-cd), but unfortunately most of the top answers there are not useful here (using an alias) or just plain bad ideas (any of the ones that try to make it work via a script). Use a function. – Gordon Davisson Jan 25 '21 at 22:08

1 Answers1

0

When working in / with bash There is no need to cd (it's actually considered "poor form"). cd is "meant" for command line usage -- Though it will work in some cases programmatically, it's easiest and best practice to use the directory when working with it rather than trying to change directory into it.

Simply "use" the full directory to do whatever you intend on "doing" with it .. IE

mkdir "$1" && echo "test" > $1/test.txt

NOTE

In case I read your question wrong, and you want the shell to change directory is a little trickier. The sub-shell (or bash script) has it's own concept of directory .. So no matter "where" you tell it to cd, it will only apply to that sub-shell and not the main shell (or command line). One way to get around this is to use alias

alias dir="cd $M1"
Zak
  • 6,976
  • 2
  • 26
  • 48