From ee1ec503225ae41b6213aff3b7da1db0141bce19 Mon Sep 17 00:00:00 2001 From: Julian Prein Date: Wed, 13 Jul 2022 17:24:29 +0200 Subject: [PATCH] zsh:funcs:mkcd: Improve argument parsing Do not switch into a directory, if multiple were created. Support flags given at the end of the commandline (e.g. `mkdir foo/bar -p`) --- .config/zsh/zshrc.d/40-functions.zsh | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/.config/zsh/zshrc.d/40-functions.zsh b/.config/zsh/zshrc.d/40-functions.zsh index 64c63bb..52d8b4f 100644 --- a/.config/zsh/zshrc.d/40-functions.zsh +++ b/.config/zsh/zshrc.d/40-functions.zsh @@ -20,18 +20,28 @@ bwpwd() { fi } -# creates directory and changes into it +# mkdir wrapper that changes into the created directory if only one was given mkcd () { # Create directory - mkdir "$@" - # shift arguments if mkdir options were used - while [[ $# -gt 1 ]]; do - shift + mkdir "$@" || return + + # Remove flags and their arguments + nargs="$#" + for ((i = 0; i < nargs; i++)); do + if [[ ${1[1]} = '-' ]]; then + # When `-m` is given, shift it's MODE argument as well + ! [[ $1 =~ ^-([^-].*)?m$ ]] || { shift; i+=1 } + + shift + else + set -- "${@:2}" "$1" + fi done - if [[ -d "$1" ]]; then - cd "$1" - pwd - fi + + # cd into the created directory if only one was specified + [[ $# -eq 1 && -d $1 ]] || return 0 + cd "$1" + pwd } # Encode and decode qr-codes