Reputation: 21
In an bash shell script I am receiving a list of argument in $@ which are : a b c d a c e Depending of the argument I need to do something specific with a case structure. But I only want to do it for a b c d e
I should only use bash and not any other language...I can use awk for example
for argument in "$@"
do
case $argument in
a)
.....
Have tried many things but without success
Any help much appreciated
Upvotes: 2
Views: 490
Reputation: 141995
You could print, then sort unique, then print quoted the list and re-eval into arguments. With GNU tools:
set -- a b c d a c e
tmp=$(printf "%s\0" "$@" | sort -uz | xargs -0 printf "%q ")
eval set -- "$tmp"
Upvotes: 1
Reputation: 295894
Use an associative array to track arguments you've already seen. Note that this requires bash 4.0 or later; the 3.2.x release that Apple ships is too old, as it only supports numerically-indexed arrays (declare -a
, but not declare -A
).
#!/usr/bin/env bash
case $BASH_VERSION in ''|[0-3].*) echo "ERROR: Bash 4.0+ required" >&2; exit 1;; esac
declare -A seen=( )
declare -a deduped=( )
for arg in "$@"; do # iterate over our argument list
[[ ${seen[$arg]} ]] && continue # already seen this? skip it
seen[$arg]=1 # mark as seen going forward...
deduped+=( "$arg" ) # ...and add to our new/future argv
done
set -- "${deduped[@]}" # replace "$@" with contents of deduped array
Upvotes: 5