3

I'm trying to write a very simple mkcd command:

#!/bin/bash
mkdir $1
cd $1

The directory is created but the change directory part doesn't seem to run.

Update based on comment:

mkcd () {
  mkdir "$1"
  cd "$1"
}

I'm trying to run it first as a local file:

./mkcd

My end location is /opt/bin, neither location seems to work.

2
  • 4
    Note that the call to cd does run - but its effect is lost as soon as the subshell running the script dies. Commented Dec 8, 2016 at 13:38
  • My extended version of PSkocik's answer: mkcd() { if [ ! -d "$@" ];then mkdir -p "$@" ;fi; cd "$@"; } (Posted as comment because answering is disabled here.). Commented Jun 20, 2019 at 20:31

1 Answer 1

8

It needs to be a function:

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

A script will get run inside its own separate process. Changing directories there will have no effect on the parent shell (neither will changing directories inside a subshell as in (cd /tmp)).

9
  • With that it doesn't seem to make the folder. I will double check that I did it exact. Commented Dec 8, 2016 at 13:39
  • 2
    I think problem was I didn't close the terminal to refresh my .bashrc Commented Dec 8, 2016 at 13:55
  • 1
    My version: mkcd() { if [ ! -e "$@" ];then mkdir -p "$@" && cd "$@";fi; } . Commented Jun 20, 2019 at 20:20
  • 1
    @neverMind9 I kind of assume it was for interactive use and therefore time wasn't of the essence. [ -d "$1" ] || mkdir -p "$1" is good for saving time on process start overheads in scripts, though. (I think -d is better than -e because then you'll run mkdir iff the arg isn't a directory and mkdir will then generate an error message for you). Commented Jun 20, 2019 at 20:25
  • 1
    @PSkocik Sorry for the mistake in the last one. I updated it (and moved the “cd” part outside of the “if” request): mkcd() { if [ ! -d "$@" ];then mkdir -p "$@" ;fi; cd "$@"; } . Commented Jun 20, 2019 at 20:28

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.