我有一个 bash 脚本,它是这样的:
#!/bin/bash
if [ $1 = "--test" ] || [ $1 = "-t" ]; then
echo "Testing..."
testing="y"
else
testing="n"
echo "Not testing."
fi
Run Code Online (Sandbox Code Playgroud)
所以我想要做的不仅是用./script --testor运行它./script -t,而且不带参数(只是./script),但似乎如果我用当前代码这样做,输出只是:
./script: line 3: [: =: unary operator expected
./script: line 3: [: =: unary operator expected
Not testing.
Run Code Online (Sandbox Code Playgroud)
那么我如何对其进行编程,以便在没有任何参数的else情况下运行它只会在不抛出错误的情况下执行该操作?我究竟做错了什么?
Jay*_*Eye 16
几种方式;最明显的两个是:
$1双引号:if [ "$1" = "--test" ]更好的是,使用 getopts。
您需要在 if 条件中引用您的变量。代替:
if [ $1 = "--test" ] || [ $1 = "-t" ]; then
Run Code Online (Sandbox Code Playgroud)
和:
if [ "$1" = '--test' ] || [ "$1" = '-t' ]; then
Run Code Online (Sandbox Code Playgroud)
然后它将起作用:
? ~ ./test.sh
不测试。
始终双引号您的变量!
在 shell 脚本中使用长选项的“正确方法”是通过getopt GNU 实用程序。还有bash 内置的 getopts,但它只允许诸如-t. 可以在此处getopt找到一些用法示例。
这是一个演示我如何处理你的问题的脚本。大多数步骤的说明都作为注释添加到脚本本身中。
#!/bin/bash
# GNU getopt allows long options. Letters in -o correspond to
# comma-separated list given in --long.
opts=$(getopt -o t --long test -- "$*")
test $? -ne 0 && exit 2 # error happened
set -- $opts # some would prefer using eval set -- "$opts"
# if theres -- as first argument, the script is called without
# option flags
if [ "$1" = "--" ]; then
echo "Not testing"
testing="n"
# Here we exit, and avoid ever getting to argument parsing loop
# A more practical case would be to call a function here
# that performs for no options case
exit 1
fi
# Although this question asks only for one
# option flag, the proper use of getopt is with while loop
# That's why it's done so - to show proper form.
while true; do
case "$1" in
# spaces are important in the case definition
-t | --test ) testing="y"; echo "Testing" ;;
esac
# Loop will terminate if there's no more
# positional parameters to shift
shift || break
done
echo "Out of loop"
Run Code Online (Sandbox Code Playgroud)
通过一些简化和删除注释,可以将其简化为:
#!/bin/bash
opts=$(getopt -o t --long test -- "$*")
test $? -ne 0 && exit 2 # error happened
set -- $opts
case "$1" in
-t | --test ) testing="y"; echo "Testing";;
--) testing="n"; echo "Not testing";;
esac
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1479 次 |
| 最近记录: |