ter*_*don 35
在大多数情况下,[
是一个内置的 shell,相当于test
. 但是,就像test
,它也作为独立的可执行文件存在:这就是/bin/[
您所看到的。您可以使用type -a [
(在 Arch Linux 系统上,运行bash
)来测试:
$ type -a [
[ is a shell builtin
[ is /bin/[
Run Code Online (Sandbox Code Playgroud)
所以,在我的系统上,我有两个[
:我的 shell 的内置文件和/bin
. 可执行文件记录在man test
:
TEST(1) User Commands TEST(1)
NAME
test - check file types and compare values
SYNOPSIS
test EXPRESSION
test
[ EXPRESSION ]
[ ]
[ OPTION
DESCRIPTION
Exit with the status determined by EXPRESSION.
[ ... ]
Run Code Online (Sandbox Code Playgroud)
正如你可以在手册页的摘录见上面引述,test
和[
是等价的。该/bin/[
和/bin/test
命令由POSIX指定这就是为什么你会尽管许多炮弹也为他们提供的内建找到他们。它们的存在确保了以下结构:
[ "$var" -gt 10 ] && echo yes
Run Code Online (Sandbox Code Playgroud)
即使运行它们的 shell 没有[
内置函数也能工作。例如,在tcsh
:
> which [
/sbin/[
> set var = 11
> [ "$var" -gt 10 ] && echo yes
yes
Run Code Online (Sandbox Code Playgroud)
Hau*_*ing 12
这用于 shell 脚本中的条件测试。这个程序的另一个名字是test
:
if [ 1 -lt 2 ]; then ...
Run Code Online (Sandbox Code Playgroud)
这看起来像 shell 语法,但不是。通常[
是内置的 shell,但可能作为后备,它作为外部命令存在。
请参阅 中的“条件表达式”块man bash
。
小智 9
[
与相同的命令test
。在某些 *nix 系统上,一个只是到另一个的链接。例如,如果您运行:
strings /usr/bin/test
strings /usr/bin/[
Run Code Online (Sandbox Code Playgroud)
您将看到相同的输出。
大多数 sh-shells/posix-shells 包括内置[
和test
命令。对于 也是如此echo
。/bin/echo
大多数 shell 中都有一个命令和一个内置命令。这就是为什么有时您会觉得,例如,echo
在不同系统上的工作方式不同的原因。
test
或者[
只返回退出代码0
或1
。如果测试成功,退出代码为 0。
# you can use [ command but last argument must be ]
# = inside joke for programmers
# or use test command. Args are same, but last arg can't be ] :)
# so you can't write
# [-f file.txt] because [-f is not command and last argument is not ]
# after [ have to be delimiter as after every commands
[ -f file.txt ] && echo "file exists" || echo "file does not exist"
test -f file.txt && echo "file exists" || echo "file does not exist"
[ 1 -gt 2 ] && echo yes || echo no
test 1 -gt 2 && echo yes || echo no
# use external command, not builtin
/usr/bin/[ 1 -gt 2 ] && echo yes || echo no
Run Code Online (Sandbox Code Playgroud)
您还可以使用[
带if
:
if [ -f file.txt ] ; then
echo "file exists"
else
echo "file does not exist"
fi
# is the same as
if test -f file.txt ; then
echo "file exists"
else
echo "file does not exist"
fi
Run Code Online (Sandbox Code Playgroud)
但是您可以if
与每个命令一起使用,if
用于测试退出代码。例如:
cp x y 2>/dev/null && echo cp x y OK || echo cp x y not OK
Run Code Online (Sandbox Code Playgroud)
或者,使用if
:
if cp x y 2>/dev/null ; then
echo cp x y OK
else
echo cp x y not OK
fi
Run Code Online (Sandbox Code Playgroud)
您可以仅使用test
命令测试保存到变量的退出代码来获得相同的结果stat
:
cp x y 2>/dev/null
stat=$?
if test "$stat" = 0 ; then
echo cp x y OK
else
echo cp x y not OK
fi
Run Code Online (Sandbox Code Playgroud)
您也可以使用[[ ]]
and(( ))
进行测试,但它们与[
and 不同test
,尽管语法几乎相同:
最后,要找出什么是命令,您可以使用:
type -a command
Run Code Online (Sandbox Code Playgroud)