ls -rlt 'file_name_not_exits.txt'
echo "$?" && if [ "$?" == "1" ]; then echo "错误存在" fi
syntax error: unexpected end of file
ls -rlt 'file_name_not_exits.txt'
echo "$?" && if [ "$?" == "1" ]; then echo "错误存在" fi
syntax error: unexpected end of file
这个 shell 脚本有几个小问题:
if [ "$?" == "1" ]; then echo "错误存在" fi
错误主要在这段,调试sh脚本的好方法是,把这些命令写在文件中,在文件开头添加 set -xv
开启脚本跟踪和可视化(文件内容如下)
#!/bin/bash
set -xv
ls -rlt 'file_name_not_exits.txt'
echo "$?" && if [ "$?" == "1" ]; then echo "错误存在" fi
运行,输出如下信息:
...
echo "$?" && if [ "$?" == "1" ]; then echo "错误存在" fi./i.sh: 3: ./i.sh: Syntax error: end of file unexpected (expecting "fi")
按照提示,fi
周围可能有错,if then fi
是三个语句,出现在同一行,每段语句都要加分号,then
之前缺少了分号。加上分号,再运行,输出:
...
echo "$?" && if [ "$?" == "1" ]; then echo "错误存在"; fi+ echo 2
/+ [ 0 == 1 ]
./i.sh: 3: [: 0: unexpected operator
"unexpected operator" 说明 [ ]
内操作异常,shell 的字符串比较是 =
而不是 ==
,这一点和大部分程序语言不一样。
看上面的倒数第二行,[ ]
中的 $?
值为 0,它是 echo $?
的返回值,不出意外,这个 "$?" 永远是 "0",我想这可能不是你想要的。
如果是我,要是在终端运行这些命令,我可能会这样写:
ls -rlt 'file_name_not_exits.txt'
ret="$?"
echo "$ret" && if [ "$ret" -eq 1 ]; then echo "错误存在"; fi
unset ret
但有多语句时,最好写在一个文件里,运行起来方便,也不会影响当前的运行环境。
换成这样吧?