Open yeahwu opened 4 years ago
续姥爷的文章,讲讲一个经常引发疑惑的地方。
姥爷的代码里有:
[ -f file.txt ] && echo "File exists" || echo "File doesn't exist"
这是在测试file.txt
是否存在。这种语法会让很多不熟悉bash的人疑惑:传统上条件判断是通过if
语句进行的,那么为什么[ -f file.txt ]
也能正常使用呢?
test
命令的缩写根据man [
的内容:
NAME
test, [ -- condition evaluation utility
SYNOPSIS
test expression
[ expression ]
DESCRIPTION
The test utility evaluates the expression and, if it evaluates to true, returns a zero (true) exit status; otherwise it returns 1 (false). If there
is no expression, test also returns 1 (false).
All operators and flags are separate arguments to the test utility.
The following primaries are used to construct expression:
-b file True if file exists and is a block special file.
-c file True if file exists and is a character special file.
...
可以看到这两种写法是等价的:
test expression
[ expression ]
所以姥爷的例子:
[ -f file.txt ] && echo "File exists" || echo "File doesn't exist"
等价于:
test -f file.txt && echo "File exists" || echo "File doesn't exist"
因为[
本身是一个命令,就可以理解为什么方括号里需要使用空格:
[ -f file.txt ]
这是一个正确命令。而:
[-f file.txt ]
会被bash理解成寻找可执行文件[-f
,它当然找不到,所以会出错:
bash-3.2$ [-f file.txt ]
bash: [-f: command not found
@alicesu55 解释得非常详尽,受益匪浅。Nice
https://starts.sh/posts/linux_command.html
在一行中运行两个或多个命令可以节省大量时间,并帮助在Linux中变得更加高效和高效。 在Linux中,可以通过三种方式在一行中运行多个命令: