bash script to create and cd to directory with spaces in name [duplicate] bash script to create and cd to directory with spaces in name [duplicate] unix unix

bash script to create and cd to directory with spaces in name [duplicate]


When you cd from within the script, your directory is changed within the script, but not within the calling shell. The working directory in your interactive shell is set by cd commands in THAT shell, not inside programs that are run by it.

If you want your script to be able to change the directory of your interactive shell, then you'll probably need to set up a bash function. For example, the following could be added to your .bash_profile:

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

Since this function runs within the context of your interactive shell, rather than spawning a subshell or child process, the directory changes it does are retained after it exits.


Another option, if you need/want to make your directory creation script a standalone tool, is to model things after mktemp, which creates what it needs to, and then returns the name of what it created to stdout. Thus, with the following script, perhaps called mkcd:

#!/bin/bashif mkdir -p "$*"; then  cd -P "$*"  pwd  r=0else  r=$?fiexit $r

Then in your calling script, you could run this like:

#!/bin/bashd=$(mkcd Hello World)if [ ! -d "$d" ]; then  echo "ERROR: I can't go on like this" >&2  exit 1ficd "$d": do your stuff

Note that the error checking remains a good idea even if it seems redundant, as one could fall victim to accidental or intentional unpredictable behaviour if special characters or odd formatting were used to build the directory name.


With a bit more research, I've discovered that this is because the script is a child process and cannot effect the parent shell. That is to say, the script will cd for its own purposes. I could, for example, change the code to the following:

#!/bin/bashdir=$1mkdir -v "$dir"cd "$dir"touch test.file

And run

$ bash test "Hello World"

And the result would be the file test.file appearing in ./Hello\ World/, however when the script finishes, I will still be in the previous working directory.

A sloppy way of getting the result I wanted, which is to cd into the new directory, is to spawn a new session within the script using exec bash.


Your script is (mostly) fine, as long as you use cd "$1" as you mentioned in the question. The problem is that you need to make sure the full directory name is actually passed as a single argument.

$ bash test "Hello World"

Then in your script

# Omitting unused $wd# Omitting $fulldir, which appeared to be for debugging purposes onlydir=$1mkdir -v "$dir"cd "$dir"