7

我正在修复一些我经常看到的旧 bash 脚本

if [[ -n $VARIABLE ]]; then 

语法我试图用谷歌搜索,但可以找到为什么使用“-n”,以下是我所知道的

Comparisons:
  -eq   equal to
  -ne   not equal to
  -lt   less than
  -le   less than or equal to
  -gt   greater than
  -ge   greater than or equal to

文件操作:

  -s    file exists and is not empty
  -f    file exists and is not a directory
  -d    directory exists
  -x    file is executable
  -w    file is writable
  -r    file is readable

有人会告诉我 -n 做什么吗?

4

3 回答 3

16

help test会告诉你:

String operators:

  ....

  -n STRING
     STRING      True if string is not empty.
于 2013-10-28T07:15:13.580 回答
3

如果$VARIABLE是一个字符串,那么[ -n $VARIABLE ]如果 的长度$VARIABLE不为零,则为真。

此外,[ -n $VARIABLE ]等价于:[ $VARIABLE ],当且仅当$VARIABLE是一个字符串。

更多关于:if 简介

于 2013-10-28T07:30:46.970 回答
0

和循环中使用的各种测试来自Unix命令本身。查看这些不同的测试是什么的一种简单方法是查看测试手册页。[[ ... ]][ ... ]ifwhiletest

在 Unix 中,/bin/[命令实际上是命令的硬链接/bin/test。在早期的 Unix 系统中,你会这样写:

if test -n $parameter
then
    echo "Parameter has a value"
fi

或者

if test $foo = $bar
then
    echo "Foo and Bar are equal"
fi

/bin/[创建,因此您可以执行以下操作:

if [ -n $parameter ]
then
    echo "Parameter has a value"
fi

和这个

if [ $foo = $bar ]
then
    echo "Foo and Bar are equal"
fi

这解释了为什么有趣的语法以及为什么在方括号和里面的参数之间需要一个空格。

[[ ... ]]实际上是Korn shellism ... 我的意思是 BASH借用的 POSIX shellism 。它被引入以允许模式匹配测试 ( ) 并且在 shell 内部,因此它对 shell 命令行扩展问题不太敏感。例如:[[ $foo == bar* ]]

if [ $foo = $bar ]

$foo如果在以下情况下设置或未$bar设置,则将失败:

if [[ $foo = $bar ]]

即使未设置这两个变量之一也将起作用。

[[ ... ]]语法采用所有相同的测试参数,[ ... ]现在是首选参数。

于 2013-10-28T11:59:39.467 回答