Skip to content

Instantly share code, notes, and snippets.

@n1kk
Last active May 25, 2020 23:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n1kk/a2f94d8f76183cca2a7f0ae749d02c27 to your computer and use it in GitHub Desktop.
Save n1kk/a2f94d8f76183cca2a7f0ae749d02c27 to your computer and use it in GitHub Desktop.
ways to loop through script and function arguments
# 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