[英]Bash - Check If given argument exits
I have a separate shell script that runs my docker-compose environment in attached mode or detached if I pass -d
or --detach
argument.我有一个单独的 shell 脚本,它以附加模式运行我的 docker-compose 环境,或者如果我传递
-d
或--detach
参数则分离。 It works fine when I pass this argument ( ./run-env.sh -d
) but it doesn't when I run my script without any option ( ./run-env
, just getting blank output and docker-compose doesn't run), where can be a problem?当我传递这个参数时它工作正常(
./run-env.sh -d
)但是当我运行我的脚本时没有任何选项( ./run-env
,只是得到空白输出而 docker-compose 没有运行),哪里会出问题?
#!/usr/bin/env bash
for arg in "$@"; do
if [ "$arg" = '-d' ] || [ "$arg" = '--detach' ]
then
docker-compose -f docker-compose.local-environment.yml up --build -V --detach
else
docker-compose -f docker-compose.local-environment.yml up --build -V --abort-on-container-exit
fi
done
When you don't give argument, you don't even enter the for
loop, that's why nothing happens.当你不给出参数时,你甚至不会进入
for
循环,这就是什么都没有发生的原因。
#!/usr/bin/env bash
# By default, use '--abort-on-container-exit' option
abort_or_detach="--abort-on-container-exit"
# Search for a parameter asking to run in detached mode
for arg in "$@"; do
if [ "$arg" = '-d' ] || [ "$arg" = '--detach' ]
then
abort_or_detach="--detach"
fi
done
# Run with the correct option
docker-compose -f docker-compose.local-environment.yml up --build -V $abort_or_detach
Here in this script, you call one time docker-compose
, and you can manage easily the options with the for
loop在此脚本中,您调用一次
docker-compose
,您可以使用for
循环轻松管理选项
Also, with your first try, you would launch docker-compose
as many times as you have different parameters.此外,在您的第一次尝试中,您将根据不同的参数多次启动
docker-compose
。 Here, you treat them, and then do a single launch在这里,你对待他们,然后进行一次发射
for arg in "$@"
iterates over the arguments. for arg in "$@"
遍历参数。 When you pass no arguments, it iterates zero times.当您不传递任何参数时,它会迭代零次。 Instead, try something like:
相反,请尝试以下操作:
extra=--abort-on-container-exit
for arg; do
case "$arg" in
-d|--detach) extra=--detach
esac
done
docker-compose -f docker-compose.local-environment.yml up --build -V $extra
Note that this is one of those cases where you do not want to put quotes around $extra
, because if extra
is the empty string you don't want to pass anything to docker-compose.请注意,这是您不想在
$extra
周围加上引号的情况之一,因为如果extra
是空字符串,您不想将任何内容传递给 docker-compose。 (Here, the default will ensure it is not empty, but this is a fairly common pattern and there are cases where it will be the empty string.) (在这里,默认值将确保它不为空,但这是一种相当常见的模式,在某些情况下它会是空字符串。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.