在 Bash 中测试非零长度字符串:[ -n "$var";] 或 [ “$var";] [英] Test for non-zero length string in Bash: [ -n "$var" ] or [ "$var" ]

查看:30
本文介绍了在 Bash 中测试非零长度字符串:[ -n "$var";] 或 [ “$var";]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到 Bash 脚本以两种不同的方式测试非零长度的字符串.大多数脚本使用 -n 选项:

I've seen Bash scripts test for a non-zero length string in two different ways. Most scripts use the -n option:

#!/bin/bash
# With the -n option
if [ -n "$var" ]; then
  # Do something when var is non-zero length
fi

但实际上并不需要 -n 选项:

But the -n option isn't really needed:

# Without the -n option
if [ "$var" ]; then
  # Do something when var is non-zero length
fi

哪种方式更好?

同样,这是测试零长度的更好方法:

Similarly, which is the better way for testing for zero-length:

if [ -z "$var" ]; then
  # Do something when var is zero-length
fi

if [ ! "$var" ]; then
  # Do something when var is zero-length
fi

推荐答案

这是一个更完整的版本,显示了[之间的更多差异strong>(又名 test)和 [[.

This is a more complete version that shows more differences between [ (aka test) and [[.

下表显示了变量是否被引用,使用单括号还是双括号以及变量是否只包含一个空格是影响是否使用带有 -n/- 的测试的因素z 适用于检查变量.

The following table shows that whether a variable is quoted or not, whether you use single or double brackets and whether the variable contains only a space are the things that affect whether using a test with or without -n/-z is suitable for checking a variable.

     | 1a    2a    3a    4a    5a    6a   | 1b    2b    3b    4b    5b    6b
     | [     ["    [-n   [-n"  [-z   [-z" | [[    [["   [[-n  [[-n" [[-z  [[-z"
-----+------------------------------------+------------------------------------
unset| false false true  false true  true | false false false false true  true
null | false false true  false true  true | false false false false true  true
space| false true  true  true  true  false| true  true  true  true  false false
zero | true  true  true  true  false false| true  true  true  true  false false
digit| true  true  true  true  false false| true  true  true  true  false false
char | true  true  true  true  false false| true  true  true  true  false false
hyphn| true  true  true  true  false false| true  true  true  true  false false
two  | -err- true  -err- true  -err- false| true  true  true  true  false false
part | -err- true  -err- true  -err- false| true  true  true  true  false false
Tstr | true  true  -err- true  -err- false| true  true  true  true  false false
Fsym | false true  -err- true  -err- false| true  true  true  true  false false
T=   | true  true  -err- true  -err- false| true  true  true  true  false false
F=   | false true  -err- true  -err- false| true  true  true  true  false false
T!=  | true  true  -err- true  -err- false| true  true  true  true  false false
F!=  | false true  -err- true  -err- false| true  true  true  true  false false
Teq  | true  true  -err- true  -err- false| true  true  true  true  false false
Feq  | false true  -err- true  -err- false| true  true  true  true  false false
Tne  | true  true  -err- true  -err- false| true  true  true  true  false false
Fne  | false true  -err- true  -err- false| true  true  true  true  false false

如果您想知道变量是否为非零长度,请执行以下任一操作:

If you want to know if a variable is non-zero length, do any of the following:

  • 在单括号中引用变量(第 2a 列)
  • 使用 -n 并在单括号中引用变量(第 4a 列)
  • 使用带或不带引号的双括号以及带或不带 -n(第 1b - 4b 列)
  • quote the variable in single brackets (column 2a)
  • use -n and quote the variable in single brackets (column 4a)
  • use double brackets with or without quoting and with or without -n (columns 1b - 4b)

注意第 1a 列中从标记为二"的行开始,结果表明 [ 正在评估变量的内容,就好像它们是条件的一部分表达式(结果与描述列中的T"或F"隐含的断言匹配).当使用 [[ 时(第 1b 列),变量内容被视为字符串而不被评估.

Notice in column 1a starting at the row labeled "two" that the result indicates that [ is evaluating the contents of the variable as if they were part of the conditional expression (the result matches the assertion implied by the "T" or "F" in the description column). When [[ is used (column 1b), the variable content is seen as a string and not evaluated.

第 3a 列和第 5a 列中的错误是由变量值包含空格且变量未加引号引起的.同样,如第 3b 和 5b 列所示,[[ 将变量的内容计算为字符串.

The errors in columns 3a and 5a are caused by the fact that the variable value includes a space and the variable is unquoted. Again, as shown in columns 3b and 5b, [[ evaluates the variable's contents as a string.

相应地,对于零长度字符串的测试,第 6a、5b 和 6b 列显示了正确的方法.另请注意,如果否定显示出比使用相反操作更清晰的意图,则可以否定这些测试中的任何一个.例如:<代码>如果![[ -n $var ]].

Correspondingly, for tests for zero-length strings, columns 6a, 5b and 6b show the correct ways to do that. Also note that any of these tests can be negated if negating shows a clearer intent than using the opposite operation. For example: if ! [[ -n $var ]].

如果您使用 [,确保不会得到意外结果的关键是引用变量.使用[[,没关系.

If you're using [, the key to making sure that you don't get unexpected results is quoting the variable. Using [[, it doesn't matter.

被抑制的错误消息是期望一元运算符"或期望二元运算符".

The error messages, which are being suppressed, are "unary operator expected" or "binary operator expected".

这是生成上表的脚本.

#!/bin/bash
# by Dennis Williamson
# 2010-10-06, revised 2010-11-10
# for http://stackoverflow.com/q/3869072
# designed to fit an 80 character terminal

dw=5    # description column width
w=6     # table column width

t () { printf '%-*s' "$w" " true"; }
f () { [[ $? == 1 ]] && printf '%-*s' "$w" " false" || printf '%-*s' "$w" " -err-"; }

o=/dev/null

echo '     | 1a    2a    3a    4a    5a    6a   | 1b    2b    3b    4b    5b    6b'
echo '     | [     ["    [-n   [-n"  [-z   [-z" | [[    [["   [[-n  [[-n" [[-z  [[-z"'
echo '-----+------------------------------------+------------------------------------'

while read -r d t
do
    printf '%-*s|' "$dw" "$d"

    case $d in
        unset) unset t  ;;
        space) t=' '    ;;
    esac

    [ $t ]        2>$o  && t || f
    [ "$t" ]            && t || f
    [ -n $t ]     2>$o  && t || f
    [ -n "$t" ]         && t || f
    [ -z $t ]     2>$o  && t || f
    [ -z "$t" ]         && t || f
    echo -n "|"
    [[ $t ]]            && t || f
    [[ "$t" ]]          && t || f
    [[ -n $t ]]         && t || f
    [[ -n "$t" ]]       && t || f
    [[ -z $t ]]         && t || f
    [[ -z "$t" ]]       && t || f
    echo

done <<'EOF'
unset
null
space
zero    0
digit   1
char    c
hyphn   -z
two     a b
part    a -a
Tstr    -n a
Fsym    -h .
T=      1 = 1
F=      1 = 2
T!=     1 != 2
F!=     1 != 1
Teq     1 -eq 1
Feq     1 -eq 2
Tne     1 -ne 2
Fne     1 -ne 1
EOF

这篇关于在 Bash 中测试非零长度字符串:[ -n "$var";] 或 [ “$var";]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆