我input的代码与“Linux命令行:完整简介” (第369页)相同,但提示错误:
line 7 `if[ -e "$FILE" ]; then`
代码是这样的:
#!/bin/bash #test file exists FILE="1" if[ -e "$FILE" ]; then if[ -f "$FILE" ]; then echo :"$FILE is a regular file" fi if[ -d "$FILE" ]; then echo "$FILE is a directory" fi else echo "$FILE does not exit" exit 1 fi exit
我想知道是什么引入了错误? 我如何修改代码? 我的系统是Ubuntu。
if
和[
之间必须有一个空格,像这样:
#!/bin/bash #test file exists FILE="1" if [ -e "$FILE" ]; then if [ -f "$FILE" ]; then echo :"$FILE is a regular file" fi ...
这些(和他们的组合)也都是不正确的 :
if [-e "$FILE" ]; then if [ -e"$FILE" ]; then if [ -e "$FILE"]; then
另一方面这些都可以:
if [ -e "$FILE" ];then # no spaces around ; if [ -e "$FILE" ] ; then # 1 or more spaces are ok
顺便说一句,这些是相当的
if [ -e "$FILE" ]; then if test -e "$FILE"; then
这些也是等同的:
if [ -e "$FILE" ]; then echo exists; fi [ -e "$FILE" ] && echo exists test -e "$FILE" && echo exists
而且,你的脚本的中间部分对于这样的elif
会更好:
if [ -f "$FILE" ]; then echo $FILE is a regular file elif [ -d "$FILE" ]; then echo $FILE is a directory fi
(我也在echo
删除了引号,因为在这个例子中它们是不必要的)