Last active
May 25, 2020 23:17
-
-
Save n1kk/a2f94d8f76183cca2a7f0ae749d02c27 to your computer and use it in GitHub Desktop.
ways to loop through script and function arguments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# looping over all argumetns while shifting the arguments array | |
function looping-over-all-arguments-destructive() { | |
while [[ $# -gt 0 ]]; | |
do | |
opt="$1"; | |
shift; #expose next argument | |
case "$opt" in | |
"--file" ) | |
INCLUDE=$1; | |
shift;; | |
"--flag" ) | |
FLAG=1; | |
;; | |
*) echo >&2 "Invalid option: $opt"; exit 1;; | |
esac | |
done | |
} | |
# looping over arguments while removing only the proccessed ones | |
# looping-over-all-arguments 1 2 3 qwe asd | |
function looping-over-selected-arguments() { | |
local rest=() | |
for opt in "${@}" | |
do | |
case "$opt" in | |
[0-9] ) echo "proccessed $opt" ;; # 1 2 3 | |
*) rest+=("$opt") ;; | |
esac | |
done | |
some_other_function ${rest[@]} # qwe asd | |
} | |
# look at first argument, aka subcommand | |
function main() { | |
local cmd="$1"; | |
shift; | |
case "$cmd" in | |
"command" ) call_subcommand $@;; | |
*) echo >&2 "Unknown command: $cmd"; exit 1;; | |
esac | |
} | |
main $@ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment