四、shell 中的条件判断命令 test 和 [  

  test 命令可以处理 shell 脚本中的各类工作。它产生的不是一般的输出,而是可使用的退出状态。test 命令通过接受各种不同的参数,来控制要执行哪种测试。在许多系统上,test 命令与 [ 命令的作用其实是一样的,使用 [ 命令的时候,一般在结尾加上 ] 符号,使代码更具可读性。另外,需要注意一点的是,在使用 [ 命令时,[ 符号与被检查的语句之间应该留有空格shell 中通常使用 test 命令来产生控制结构所需要的条件,根据 test 命令的退出码决定是否需要执行后面的代码

bash-3.2# man test
正在重新格式化页面。请等待... 完成

User Commands test(1)

NAME
test - evaluate condition(s)

SYNOPSIS
/usr/bin/test [condition]

[ [condition] ]

sh
test [condition]

[ [condition] ]

csh
test [condition]

[ [condition] ]

ksh
test [condition]

[ [condition] ]

DESCRIPTION
The test utility evaluates the condition and indicates the
result of the evaluation by its exit status. An exit status
of zero indicates that the condition evaluated as true and
an exit status of 1 indicates that the condition evaluated
as false.

In the first form of the utility shown using the SYNOPSIS:

test [ condition ]

the square brackets denote that condition is an optional
operand and are not to be entered on the command line.

In the second form of the utility shown using the SYNOPSIS:

SunOS 5.10 Last change: 23 Aug 2002 1

User Commands test(1)

[ [ condition ] ]

the first open square bracket, [, is the required utility
name. condition is optional, as denoted by the inner pair of
square brackets. The final close square bracket, ], is a
required operand.

See largefile(5) for the description of the behavior of test
when encountering files greater than or equal to 2 Gbyte
(2^31 bytes).

The test and [ utilities evaluate the condition condition
and, if its value is true, set exit status to 0. Otherwise,
a non-zero (false) exit status is set. test and [ also set a
non-zero exit status if there are no arguments. When permis-
sions are tested, the effective user ID of the process is
used.

All operators, flags, and brackets (brackets used as shown
in the last SYNOPSIS line) must be separate arguments to
these commands. Normally these arguments are separated by
spaces.

OPERANDS
The primaries listed below with two elements of the form:

-primary_operator primary_operand

are known as unary primaries. The primaries with three ele-
ments in either of the two forms:

primary_operand -primary_operator primary_operand
primary_operand primary_operator primary_operand

are known as binary primaries.

If any file operands except for -h and -L primaries refer to
symbolic links, the symbolic link is expanded and the test
is performed on the resulting file.

SunOS 5.10 Last change: 23 Aug 2002 2

User Commands test(1)

If you test a file you own (the -r -w or -x tests), but the
permission tested does not have the owner bit set, a non-
zero (false) exit status will be returned even though the
file may have the group or other bit set for that permis-
sion.

The = and != primaries have a higher precedence than the
unary primaries. The = and != primaries always expect argu-
ments; therefore, = and != cannot be used as an argument to
the unary primaries.

The following primaries can be used to construct condition:

-a file True if file exists. (Not avail-
able in sh.)

-b file True if file exists and is a
block special file.

-c file True if file exists and is a
character special file.

-d file True if file exists and is a
directory.

-e file True if file exists. (Not avail-
able in sh.)

-f file True if file exists and is a
regular file. Alternatively, if
/usr/bin/sh users specify
/usr/ucb before /usr/bin in
their PATH environment variable,
then test will return true if
file exists and is
(not-a-directory). The csh test
and [ built-ins always use this
alternative behavior.

-g file True if file exists and its set
group ID flag is set.

SunOS 5.10 Last change: 23 Aug 2002 3

User Commands test(1)

-G file True if file exists and its
group matches the effective
group ID of this process. (Not
available in sh.)

-h file True if file exists and is a
symbolic link.

-k file True if file exists and has its
sticky bit set.

-L file True if file exists and is a
symbolic link.

-n string True if the length of string is
non-zero.

-o option True if option named option is
on. (Not available in csh or
sh.)

-O file True if file exists and is owned
by the effective user ID of this
process. (Not available in sh.)

-p file True if file is a named pipe
(FIFO).

-r file True if file exists and is read-
able.

-s file True if file exists and has a
size greater than zero.

-S file True if file exists and is a
socket. (Not available in sh.)

-t [file_descriptor] True if the file whose file
descriptor number is
file_descriptor is open and is
associated with a terminal. If

SunOS 5.10 Last change: 23 Aug 2002 4

User Commands test(1)

file_descriptor is not speci-
fied, 1 is used as a default
value.

-u file True if file exists and its
set-user-ID flag is set.

-w file True if file exists and is writ-
able. True will indicate only
that the write flag is on. The
file will not be writable on a
read-only file system even if
this test indicates true.

-x file True if file exists and is exe-
cutable. True will indicate only
that the execute flag is on. If
file is a directory, true indi-
cates that file can be searched.

-z string True if the length of string
string is zero.

file1 -nt file2 True if file1 exists and is
newer than file2. (Not available
in sh.)

file1 -ot file2 True if file1 exists and is
older than file2. (Not available
in sh.)

file1 -ef file2 True if file1 and file2 exist
and refer to the same file. (Not
available in sh.)

string True if the string string is not
the null string.

string1 = string2 True if the strings string1 and
string2 are identical.

SunOS 5.10 Last change: 23 Aug 2002 5

User Commands test(1)

string1 != string2 True if the strings string1 and
string2 are not identical.

n1 -eq n2 True if the integers n1 and n2
are algebraically equal.

n1 -ne n2 True if the integers n1 and n2
are not algebraically equal.

n1 -gt n2 True if the integer n1 is alge-
braically greater than the
integer n2.

n1 -ge n2 True if the integer n1 is alge-
braically greater than or equal
to the integer n2.

n1 -lt n2 True if the integer n1 is alge-
braically less than the integer
n2.

n1 -le n2 True if the integer n1 is alge-
braically less than or equal to
the integer n2.

condition1 -a condition2 True if both condition1 and con-
dition2 are true. The -a binary
primary is left associative and
has higher precedence than the
-o binary primary.

condition1 -o condition2 True if either condition1 or
condition2 is true. The -o
binary primary is left associa-
tive.

These primaries can be combined with the following opera-
tors:

! condition True if condition is false.

SunOS 5.10 Last change: 23 Aug 2002 6

User Commands test(1)

( condition ) True if condition is true. The parentheses
( ) can be used to alter the normal pre-
cedence and associativity. Notice also that
parentheses are meaningful to the shell
and, therefore, must be quoted.

The algorithm for determining the precedence of the opera-
tors and the return value that will be generated is based on
the number of arguments presented to test. (However, when
using the [...] form, the right-bracket final argument will
not be counted in this algorithm.)

In the following list, $1, $2, $3 and $4 represent the argu-
ments presented to test as a condition, condition1, or con-
dition2.

0 arguments: Exit false (1).

1 argument: Exit true (0) if $1 is not null. Otherwise,
exit false.

2 arguments:
o If $1 is !, exit true if $2 is
null, false if $2 is not null.

o If $1 is a unary primary, exit true
if the unary test is true, false if
the unary test is false.

o Otherwise, produce unspecified
results.

3 arguments:
o If $2 is a binary primary, perform
the binary test of $1 and $3.

o If $1 is !, negate the two-argument
test of $2 and $3.

o Otherwise, produce unspecified
results.

4 arguments:
o If $1 is !, negate the three-
argument test of $2, $3, and $4.

SunOS 5.10 Last change: 23 Aug 2002 7

User Commands test(1)

o Otherwise, the results are unspeci-
fied.

USAGE
Scripts should be careful when dealing with user-supplied
input that could be confused with primaries and operators.
Unless the application writer knows all the cases that pro-
duce input to the script, invocations like test "$1" -a "$2"
should be written as test "$1" && test "$2" to avoid prob-
lems if a user supplied values such as $1 set to ! and $2
set to the null string. That is, in cases where maximal por-
tability is of concern, replace test expr1 -a expr2 with
test expr1 && test expr2, and replace test expr1 -o expr2
with test expr1 || test expr2. But notice that, in test, -a
has higher precedence than -o, while && and || have equal
precedence in the shell.

Parentheses or braces can be used in the shell command
language to effect grouping.

Parentheses must be escaped when using sh. For example:

test \( expr1 -a expr2 \) -o expr3

This command is not always portable outside XSI-conformant
systems. The following form can be used instead:

( test expr1 && test expr2 ) || test expr3

The two commands:

test "$1"
test ! "$1"

could not be used reliably on some historical systems. Unex-
pected results would occur if such a string condition were
used and $1 expanded to !, (, or a known unary primary.
Better constructs are, respectively,

test -n "$1"
test -z "$1"

SunOS 5.10 Last change: 23 Aug 2002 8

User Commands test(1)

Historical systems have also been unreliable given the com-
mon construct:

test "$response" = "expected string"

One of the following is a more reliable form:

test "X$response" = "Xexpected string"
test "expected string" = "$response"

Notice that the second form assumes that expected string
could not be confused with any unary primary. If expected
string starts with -, (, ! or even =, the first form should
be used instead. Using the preceding rules without the
marked extensions, any of the three comparison forms is
reliable, given any input. (However, observe that the
strings are quoted in all cases.)

Because the string comparison binary primaries, = and !=,
have a higher precedence than any unary primary in the >4
argument case, unexpected results can occur if arguments are
not properly prepared. For example, in

test -d $1 -o -d $2

If $1 evaluates to a possible directory name of =, the first
three arguments are considered a string comparison, which
causes a syntax error when the second -d is encountered. is
encountered. One of the following forms prevents this; the
second is preferred:

test \( -d "$1" \) -o \( -d "$2" \)
test -d "$1" || test -d "$2"

Also in the >4 argument case:

test "$1" = "bat" -a "$2" = "ball"

Syntax errors will occur if $1 evaluates to ( or !. One of
the following forms prevents this; the third is preferred:

SunOS 5.10 Last change: 23 Aug 2002 9

User Commands test(1)

test "X$1" = "Xbat" -a "X$2" = "Xball"
test "$1" = "bat" && test "$2" = "ball"
test "X$1" = "Xbat" && test "X$2" = "Xball"

EXAMPLES
In the if command examples, three conditions are tested, and
if all three evaluate as true or successful, then their
validities are written to the screen. The three tests are:

o if a variable set to 1 is greater than 0,

o if a variable set to 2 is equal to 2, and

o if the word root is included in the text file
/etc/passwd.

/usr/bin/test
Example 1 Using /usr/bin/test

Perform a mkdir if a directory does not exist:

test ! -d tempdir && mkdir tempdir

Wait for a file to become non-readable:

while test -r thefile
do
sleep 30
done
echo'"thefile" is no longer readable'

Perform a command if the argument is one of three strings
(two variations), using the open bracket version [ of the
test command:

if [ "$1" = "pear" ] || [ "$1" = "grape" ] || [ "$1" = "apple" ]
then
command
fi
case "$1" in
pear|grape|apple) command;;
esac

SunOS 5.10 Last change: 23 Aug 2002 10

User Commands test(1)

The test built-in
The two forms of the test built-in follow the Bourne shell's
if example.

Example 2 Using the sh built-in

ZERO=0 ONE=1 TWO=2 ROOT=root

if [ $ONE -gt $ZERO ]

[ $TWO -eq 2 ]

grep $ROOT /etc/passwd >&1 > /dev/null # discard output

then

echo "$ONE is greater than 0, $TWO equals 2, and $ROOT is" \
"a user-name in the password file"

else

echo "At least one of the three test conditions is false"
fi

Example 3 Using the test built-in

Examples of the test built-in:

test `grep $ROOT /etc/passwd >&1 /dev/null` # discard output

echo $? # test for success
[ `grep nosuchname /etc/passwd >&1 /dev/null` ]

echo $? # test for failure

csh
Example 4 Using the csh built-in

@ ZERO = 0; @ ONE = 1; @ TWO = 2; set ROOT = root
grep $ROOT /etc/passwd >&1 /dev/null # discard output
# $status must be tested for immediately following grep
if ( "$status" == "0" && $ONE > $ZERO && $TWO == 2 ) then
echo "$ONE is greater than 0, $TWO equals 2, and $ROOT is" \
"a user-name in the password file"
endif

SunOS 5.10 Last change: 23 Aug 2002 11

User Commands test(1)

ksh
Example 5 Using the ksh built-in

ZERO=0 ONE=1 TWO=$((ONE+ONE)) ROOT=root
if ((ONE > ZERO)) # arithmetical comparison
[[ $TWO = 2 ]] # string comparison
[ `grep $ROOT /etc/passwd >&1 /dev/null` ] # discard output
then
echo "$ONE is greater than 0, $TWO equals 2, and $ROOT is" \
"a user-name in the password file"

else
echo "At least one of the three test conditions is false"
fi

Using -e option in sh
Example 6 Using /usr/bin/test for the -e option

If one really wants to use the -e option in sh, use
/usr/bin/test, as in the following:

if [ ! -h $PKG_INSTALL_ROOT$rLink ] && /usr/bin/test -e
$PKG_INSTALL_ROOT/usr/bin/$rFile ; then
ln -s $rFile $PKG_INSTALL_ROOT$rLink
fi

ENVIRONMENT VARIABLES
See environ(5) for descriptions of the following environment
variables that affect the execution of test: LANG, LC_ALL,
LC_CTYPE, LC_MESSAGES, and NLSPATH.

EXIT STATUS
The following exit values are returned:

0 condition evaluated to true.

1 condition evaluated to false or condition was missing.

>1 An error occurred.

ATTRIBUTES
See attributes(5) for descriptions of the following attri-
butes:

SunOS 5.10 Last change: 23 Aug 2002 12

User Commands test(1)

____________________________________________________________
| ATTRIBUTE TYPE | ATTRIBUTE VALUE |
|_____________________________|_____________________________|
| Availability | SUNWcsu |
|_____________________________|_____________________________|
| Interface Stability | Standard |
|_____________________________|_____________________________|

SEE ALSO
csh(1), ksh(1), sh(1), test(1B), attributes(5), environ(5),
largefile(5), standards(5)

NOTES
The not-a-directory alternative to the -f option is a tran-
sition aid for BSD applications and may not be supported in
future releases.

SunOS 5.10 Last change: 23 Aug 2002 13

shell脚本if语句后面的中括号[]与java的if后面的小括号不同(),实际上[左中括号相当于test命令的更多相关文章

  1. php正则:匹配(),{},[]小括号,大括号,中括号里面的内容

    php正则:匹配(),{},[]小括号,大括号,中括号里面的内容 比如有一段字符: $s='60c8 {"code":"200","message&q ...

  2. Python中的小括号()、中括号[]、花括号{}区别

    Python中最常见括号的区别: 在Python语言中最常见的括号有三种,分别是:小括号().中括号[].花括号{}:其作用也不相同,分别用来代表不同的Python基本内置数据类型. Python中的 ...

  3. Linux就该这么学--Shell脚本条件语句(二)

    1.for条件语句 先读取多个不同的变量值,然后逐一执行同一组命令. 从列表文件中读取主机地址,逐个测试是否在线. 从ipadds.txt中读取主机地址后赋值给HLIST变量后逐个ping列表中的主机 ...

  4. Linux就该这么学--Shell脚本条件语句(一)

    1.条件测试语句能够让Shell脚本根据实际工作灵活调整工作内容,例如判断系统的状态后执行指定的工作,或创建指定数量的用户,批量修改用户密码,这些都可以让Shell脚本通过条件测试语句完成. if条件 ...

  5. Shell脚本case语句

    case语句格式 case 变量 in PAT1) 执行语句 ;; PAT2) 执行语句 ;; *) 默认执行语句 ;; esac 使用示例: 编写一个shell脚本,通过提示用户输入信息,输出cpu ...

  6. shell脚本if语句的多种条件参数

    if语句有多种写法 [root@shell-yankerp sh]# [ -f file ] && echo "yes" || echo "no" ...

  7. shell脚本判断语句和循环语句

    if判断语句 exit跳出判读语句 不加exit的结果 read -n(不换行) 判断是否输入的是数字 read age[[ $age =~ ^[0-9]+$ ]]if [ $? -ne 0 ]; t ...

  8. Linux Shell脚本编程-语句控制

    过程式编程语言bash脚本编程面向过程的编程  顺序执行:默认法则,按照顺序一条一条语句执行  选择执行:分支,条件判断,符合条件的分支予以执行  循环执行:将同一段代码反复执行有限次,所以循环必须有 ...

  9. linux shell脚本常用语句

    linux shell 指令 诸如-d, -f, -e之类的判断表达式: 文件比较运算符-e filename  如果 filename存在,则为真  [ -e /var/log/syslog ]-d ...

随机推荐

  1. C学习笔记-gcc

    GNU CC(通常称为GCC)是GNU项目的编译器,它能够编译C.C++语言编写的程序 gcc的优点 使用gcc,程序员可以控制生成二进制执行文件中调试代码的数量和类型. 和其他编译器一样,gcc也可 ...

  2. DIN

    1. DIN(Deep Interest Network)优点 使用用户兴趣分布来表示用户多种多样的兴趣爱好. 使用Attention机制来实现Local Activation,局部激活相关的历史兴趣 ...

  3. C语言|作业07

    一.本周作业头 这个作业属于那个课程 C语言程序设计II 这个作业要求在哪里 https://i-beta.cnblogs.com/posts/edit;postId=11811545 我在这个课程的 ...

  4. 【CSP模拟】小凯的疑惑(DP)

    首先,这道题正解的思路是从subtask2而得来的,所以先讲一下subtask2的做法. 因为保证答案不超过long long,所以直接求最大权独立集即可:dp[u][0]表示u点一定不能取的答案,d ...

  5. [c++] 幂法求特征向量

    幂法的原理可参考此篇论文:http://d.wanfangdata.com.cn/Periodical/hnnydxxb2001Z1023 本文求解的是 3 阶矩阵最大特征值及其特征向量 下面是其 C ...

  6. [Python3] 040 文件 一般使用

    目录 文件 1. open 函数 2. with 语句 3. 先写再读 3.1 写 3.2 读 4. "位置"的查询与移动 4.1 tell() 4.2 seek(cookie, ...

  7. [转帖] Linux下面计算文件数量的方法

    Linux命令-查看目录下文件个数 2018年07月04日 10:37:07 sand_clock 阅读数 2002    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blo ...

  8. 浅谈Linux kill命令

    傻瓜常规篇: 首先,用ps查看进程,方法如下: $ ps -ef ……smx       1822     1  0 11:38 ?        00:00:49 gnome-terminalsmx ...

  9. python PEP8常用规范(看完你会感谢我的!)

    完整的规范移步传送门 pep8规范 官方文档:[https://www.python.org/dev/peps/pep-0008/](https://www.python.org/dev/peps/p ...

  10. ps -ef

    status, msg = commands.getstatusoutput("ps -ef | grep start.sh | grep -Fv grep | awk '{print $1 ...