Jon
Jon

Reputation: 373

loop minus one string from list in bash

I have a list of strings (a_001 a_002 a_003 ect.) which I would like to use in a command minus one string each time it is run. That is, I would like to run a loop where the first time a_002 and a_003 are included followed by a_001 & a_003 and then a_001 and a_002. Can this be set up in bash?

Upvotes: 2

Views: 550

Answers (2)

chepner
chepner

Reputation: 531758

Given a set of strings S, you want to use S - {x} for each x in S.

Here's one way:

 S=( a_001 a_002 a_003 )
 set -- "${S[@]}"
 for x; do
     shift                          # Removes x from the positional arguments
     echo "Use $@ without $x"       # Some action involving `S - {x}`
     set -- "$@" "$x"               # Put x back on the end, put
 done

Upvotes: 0

Gilles Quénot
Gilles Quénot

Reputation: 185530

Try this :

#!/bin/bash

x=( a_001 a_002 a_003 )

set -- "${x[@]}"

while [[ $@ ]]; do
    echo "command $@"
    shift
done

Is it what you expected ?

Output

command a_001 a_002 a_003
command a_002 a_003
command a_003

Upvotes: 1

Related Questions