I have a script that takes parameters and I want to remove given named parameters
e.g. script.sh a b c and I want to remove 'b' so that
$1 = a
$2 = c
This also must work for any given set of args such that e.g.
script.sh "a 1" b "c 2"
$1 = "a 1"
$2 = "c 2"
A previous answer said
for var in "$@"; do
case $var in
"a") echo -n $var ;;
"b") ;;
esac
done
The generic version of the previous answer should have been (in order to remove b)
for var in "$@"; do
case $var in
"b") ;;
*) echo -n $var ;;
esac
done
But this fails for multiple parameters e.g.
script.sh a b c
Output: ac
We wanted a b and we wanted them in positional parameter $1=a and $2=b
So a better answer is needed.
I presented two options, a solution to your problem and in addition a more proper way of hanlding input arguments.
To Answer your question
Looking at this little bit of code, we exclude the argument options from the values by comparing each value to our
arg_optionsarray. Hence anything define inarg_optionswill not be in the final results.The script loops over every input option, then runs another check (loop) to look for any matches in our arg options, if it's found we mark it as a value we don't want and we move on.
To expand on your question
Take this example 'script.sh' with command line options:
Here's the code, and the nice part is that it will properly handle the inputs no matter what order they are passed to the script:
What are we doing in the script, we are defining a function to read in the options and set the global variables
get_user_input_options. Look at how it is being called, it is taking in all of the command line inputs for handling with the"$@"option. Note: if you don't want it to be a script just remove the function line and it's closing bracket.Then it is using a while loop to step over every option, but when it finds a match for an option it sets the value and shifts forward as that had the value of the option. It continues to step through the inputs until completed.
You will also notice that I set the global variable 'mode' to something so if the script is called without that option, it will be set to a default value.