Bash 数组循环只取第一个条目

Bash array loop only takes the first entry

晚上好,

我只是尝试停止数组中定义的一些 docker 容器。 但是只有第一个停了四次。

CONTAINERTOSTOP=(webgrabplus Nextcloud ddclient MariaDB-10.6)

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

我的脚本只停止了 webgrabplus 容器,但是停止了四次 我认为循环有效。

我哪里错了?

您正在停止 $CONTAINERTOSTOP。你想要 $constopping.

您还缺少 ;docker 命令后的换行符。

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

(当然,@ufopilot 的回答在特定情况下甚至更好,但我让我的回答代表“if 你想要一个循环...”的情况。 )

停止使用(没有循环):

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