我输入的代码与Linux命令行相同:完整介绍,第369页,但提示错误:
line 7 `if[ -e "$FILE" ]; then`
Run Code Online (Sandbox Code Playgroud)
代码如下:
#!/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
Run Code Online (Sandbox Code Playgroud)
我想知道是什么引入了这个错误?我该如何修改代码?我的系统是Ubuntu.
Sto*_*ica 59
if
和之间必须有空格[
,如下所示:
#!/bin/bash
#test file exists
FILE="1"
if [ -e "$FILE" ]; then
if [ -f "$FILE" ]; then
echo :"$FILE is a regular file"
fi
...
Run Code Online (Sandbox Code Playgroud)
这些(及其组合)也都是错误的:
if [-e "$FILE" ]; then
if [ -e"$FILE" ]; then
if [ -e "$FILE"]; then
Run Code Online (Sandbox Code Playgroud)
另一方面,这些都可以:
if [ -e "$FILE" ];then # no spaces around ;
if [ -e "$FILE" ] ; then # 1 or more spaces are ok
Run Code Online (Sandbox Code Playgroud)
顺便说一下这些是等价的:
if [ -e "$FILE" ]; then
if test -e "$FILE"; then
Run Code Online (Sandbox Code Playgroud)
这些也是等价的:
if [ -e "$FILE" ]; then echo exists; fi
[ -e "$FILE" ] && echo exists
test -e "$FILE" && echo exists
Run Code Online (Sandbox Code Playgroud)
并且,脚本的中间部分会更好,elif
如下所示:
if [ -f "$FILE" ]; then
echo $FILE is a regular file
elif [ -d "$FILE" ]; then
echo $FILE is a directory
fi
Run Code Online (Sandbox Code Playgroud)
(我也删除了引号echo
,因为在这个例子中它们是不必要的)
归档时间: |
|
查看次数: |
58955 次 |
最近记录: |