2

This question already has an answer here:

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.

marked as duplicate by PSkocik, roaima, dhag, GAD3R, Jeff Schaller Dec 8 '16 at 14:29

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 4
    Note that the call to cd does run - but its effect is lost as soon as the subshell running the script dies. – D_Bye Dec 8 '16 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.). – neverMind9 Jun 20 at 20:31
4

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)).

  • With that it doesn't seem to make the folder. I will double check that I did it exact. – Philip Kirkbride Dec 8 '16 at 13:39
  • 2
    I think problem was I didn't close the terminal to refresh my .bashrc – Philip Kirkbride Dec 8 '16 at 13:55
  • 1
    My version: mkcd() { if [ ! -e "$@" ];then mkdir -p "$@" && cd "$@";fi; } . – neverMind9 Jun 20 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). – PSkocik Jun 20 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 "$@"; } . – neverMind9 Jun 20 at 20:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.