Home > Software design >  Bash array loop only takes the first entry
Bash array loop only takes the first entry

Time:05-18

Good evening,

i just try to stop some docker containers defined in an array. But only the first one is stopped but four times.

CONTAINERTOSTOP=(webgrabplus Nextcloud ddclient MariaDB-10.6)

for constopping in "${CONTAINERTOSTOP[@]}"; do                      
docker container stop $CONTAINERTOSTOP done

My script only stops the webgrabplus container but for four times so i think the loop works.

Where is my fault here ?

CodePudding user response:

You are stopping $CONTAINERTOSTOP. You want $constopping.

You are also either missing a ; or a newline after the docker command.

for constopping in "${CONTAINERTOSTOP[@]}"
do
    docker container stop $constopping
done

(Of course, @ufopilot's answer is even better in the specific case, but I let my answer stand for the "if you want a loop..." case.)

CodePudding user response:

To stop just using (without loop):

CONTAINERTOSTOP=(webgrabplus Nextcloud ddclient MariaDB-10.6)
docker stop ${CONTAINERTOSTOP[@]}
# or 
CONTAINERTOSTOP="webgrabplus Nextcloud ddclient MariaDB-10.6"
docker stop $CONTAINERTOSTOP
  •  Tags:  
  • bash
  • Related