Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Post History

77%
+5 −0
Q&A In a bash shell script, how to filter the command line argument list to unique entries only, for processing each?

The solution is to use an associative array to store what you've already seen: #!/bin/bash unset seen declare -A seen for arg in "$@" do if [[ -z "${seen[$arg]}" ]] then ...

posted 3y ago by celtschk‭

Answer
#1: Initial revision by user avatar celtschk‭ · 2021-09-28T17:58:47Z (about 3 years ago)
The solution is to use an associative array to store what you've already seen:

```bash
#!/bin/bash

unset seen
declare -A seen

for arg in "$@"
do
    if [[ -z "${seen[$arg]}" ]]
    then
        echo "Doing something omplicated with $arg"
        seen["$arg"]=1
    fi
done
```
The `unset seen` is just in case the caller had an exported variable named `seen`. The `declare -A seen` tells bash to treat `seen` as an associative array, that is, it takes arbitrary strings as index.

The loop then tests for each argument whether it has not yet been seen (in which case `"${seen[arg]}"` is empty). If so, it processes it and then marks it as seen by storing something in `seen["$arg"]` (what it stores doesn't really matter as long as it is not empty; if you want, you can store additional information about the argument here, e.g. the result of processing this argument).