June 5, 2015 - coding bash
Simulating mkdir -p in bash

Xavier Geerinck
When we are working with systems that do not support special cases then we need to simulate. That is why it is handy to create different simulations of already existing solutions.
In this case we will create a solution that is going to replicate the mkdir -p command in bash.
The code for this is pretty straightforward:
# Simulate mkdir -pABSOLUTE_PATH=0if [[ ${1:0:1} == "/" ]];thenABSOLUTE_PATH=1fiecho "Path: ${ABSOLUTE_PATH}"# If absolute, cd to /if [[ $ABSOLUTE_PATH == 1 ]];thencd /fi# Start processing the path creationIFS='/' read -ra dir <<< $1for i in "${dir[@]}"; do# If empty, skipif [[ $i == "" ]];thencontinuefi# Determine if dir exists, if not create itif [[ ! -d $i ]];thenmkdir "$i"fi# Descend into the new dircd "$i"done
We can now call this program by executing:
./program relativepath/1/2/3/4./program /absolutepath/1/2/3/4