Last active
March 15, 2024 13:19
-
-
Save squito/98b3e2cf9446cf96e5efedbf3ada9f71 to your computer and use it in GitHub Desktop.
remove an arg from a command line argument in bash
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
#!/bin/bash | |
# this is a demo of how to remove an argument given with the [-arg value] notation for a specific | |
# [arg] (-T in this case, but easy to modify) | |
echo $@ | |
echo $# | |
i=0 | |
ORIGINAL_ARGS=("$@") | |
TRIMMED_ARGS=() | |
while [ $i -lt ${#ORIGINAL_ARGS[@]} ]; do | |
arg=${ORIGINAL_ARGS[$i]} | |
echo "i = $i; oa[i] = $arg" | |
if [ $arg == "-T" ]; then | |
# we want to remove both the "-T" *AND* the following arg. So we advance i here, | |
# and also once more outside of the for loop. | |
i=$((i + 1)) # careful! ((i++)) will kill your script if you use "set -e" | |
else | |
TRIMMED_ARGS+=($arg) | |
fi | |
i=$((i + 1)) # careful! ((i++)) will kill your script if you use "set -e" | |
done | |
echo "TRIMMED_ARGS = ${TRIMMED_ARGS[@]}; length = ${#TRIMMED_ARGS[@]}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
oh thanks for pointing this out @kczx3 . I assume you had an argument with a space in it? I think quotes around
$arg
in both places would have also worked (but I admit, my bash isn't great). Probably double brackets are fine too.