尝试设置规则,如果某个变量到位,有人可以识别我在这里丢失的 wtf 吗?
测试.sh:
#!/bin/bash
args=($@)
if [ "$@" = "--cron" ]; then
echo "WORKS!";
else echo "FAILS"
fi
./test.sh
的输出:
./test.sh: line 3: [: =: unary operator expected
FAILS
但是,当我运行 ./test.sh --cron
时,它起作用了,并且输出了 WORKS
。
最佳答案
执行此操作的正确方法会有所不同,具体取决于您要执行的操作。如果你想检查第一个参数是否是--cron,使用这个:
if [ "$1" = "--cron" ]; then
如果你想检查 only 参数是否是 --cron,使用这个:
if [ "$*" = "--cron" ]; then
(请注意,这是极少数情况之一,其中 "$*"
是做某事的正确方法——它扩展到所有由空格分隔的参数,但被视为单个单词解析目的。)
如果你想检查任何参数是否是--cron,使用这个:
cronopt=false
for argument; do
if [ "$argument" = "--cron" ]; then
cronopt=true
break # note: if you are scanning the arguments for other things too, remove this
fi
done
if $cronopt; then
...
顺便说一句,我不确定你使用 args=($@)
行的目的是什么,但是如果你想将参数存储在数组中,正确的方法是args=("$@")
-- 引号阻止它在将 args 放入数组之前进行分词、文件名扩展等。
关于linux - Bash ARGS 帮助 - 获取随机错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12443752/