Answers:
在大多数情况下,[是内置的Shell并等效于test。但是,就像一样test,它也作为独立的可执行文件存在:这就是/bin/[您所看到的。您可以使用type -a [(在Arch Linux系统上,运行bash)进行测试:
$ type -a [
[ is a shell builtin
[ is /bin/[
因此,在我的系统上,我有两个[:我的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.
[ ... ]
正如你可以在手册页的摘录见上面引述,test和[是等价的。该/bin/[和/bin/test命令由POSIX指定这就是为什么你会尽管许多炮弹也为他们提供的内建找到他们。它们的存在确保了类似的构造:
[ "$var" -gt 10 ] && echo yes
即使运行它们的shell没有[内置功能,它也将起作用。例如,在tcsh:
> which [
/sbin/[
> set var = 11
> [ "$var" -gt 10 ] && echo yes
yes
sh是,dash但我认为救援系统/bin/sh不使用busybox。你确定吗?
这用于外壳程序脚本中的条件测试。该程序的另一个名称是test:
if [ 1 -lt 2 ]; then ...
看起来像Shell语法,但事实并非如此。通常[是内置的Shell,但可能作为后备它作为外部命令存在。
参见中的块“条件表达式” man bash。
[与相同的命令test。在某些* nix系统上,一个只是到另一个的链接。例如,如果您运行:
strings /usr/bin/test
strings /usr/bin/[
您将看到相同的输出。
大多数SH-壳/ POSIX壳包括内置[和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
您还可以使用[带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
但是您可以if与每个命令一起使用,if用于测试退出代码。例如:
cp x y 2>/dev/null && echo cp x y OK || echo cp x y not OK
或者,使用if:
if cp x y 2>/dev/null ; then
echo cp x y OK
else
echo cp x y not OK
fi
您可以仅使用以下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
您也可以使用[[ ]]和(( ))进行测试,但是尽管语法几乎相同,但它们与[和并不test相同:
最后,要找出什么是命令,可以使用:
type -a command
cmp /usr/bin/[ /usr/bin/test也可以使用哈希sha256sum /usr/bin/[ /usr/bin/test而不是strings。在我的系统(openSUSE Tumbleweed)上,BTW并不相同(但是)。
[内置功能的shell只是其作者决定不添加其中一个的shell。tcsh没有一个[例如内置。