Passing arguments to functions

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

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.