September 2018
Beginner
186 pages
4h 30m
English
If we try to implement our mkcd alias attempt from the previous section in functions, we meet with more success than our attempt with aliases. Here's one possible implementation:
bash$ mkcd() { mkdir -p -- "$1" && cd -- "$1" ; }
This function works as we wanted, ensuring the directory is created before we try to change into it:
bash$ pwd /home/bashuser bash$ mkcd createme bash$ pwd /home/bashuser/createme
Note that this mkcd function runs more than one command in its body: a mkdir call, and a cd call. It also includes the "$1" string, which expands to the value of the first positional parameter passed to the function. We can see this in action with set -x:
bash$ set -x bash$ mkcd createme + mkcd createme + mkdir ...
Read now
Unlock full access