针对-n选项测试中的bash脚本总是返回true [英] Testing against -n option in BASH scripts always returns true

查看:99
本文介绍了针对-n选项测试中的bash脚本总是返回true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个bash脚本,其中我想检查是否有提供了具体的参数。我注意到 [-n参数] 测试的一个奇怪的(至少对我来说)的行为。对于下面的脚本:

I am writing a bash script, in which I am trying to check if there are particular parameters provided. I've noticed a strange (at least for me) behavior of [ -n arg ] test. For the following script:

#!/bin/bash

if [ -n $1 ]; then
    echo "The 1st argument is of NON ZERO length"
fi

if [ -z $1 ]; then
    echo "The 1st argument is of ZERO length"
fi

我得到的结果如下:

I am getting results as follows:


  1. 不带参数:

xylodev@ubuntu:~$ ./my-bash-script.sh
The 1st argument is of NON ZERO length
The 1st argument is of ZERO length


  • 与参数:

    xylodev@ubuntu:~$ ./my-bash-script.sh foobar
    The 1st argument is of NON ZERO length
    


  • 我已经发现了封闭 $ 1 在双引号给我的结果不如预期,但我仍然不知道的为什么当报价均为测试返回true不使用和脚本被称为不带参数吗似乎 $ 1 为空的话,那么 [-n $ 1] 应该返回假的,不应该吗?

    I've already found out that enclosing $1 in double quotes gives me the results as expected, but I still wonder why both tests return true when quotes are not used and the script is called with no parameters? It seems that $1 is null then, so [ -n $1 ] should return false, shouldn't it?

    推荐答案

    引用它。

    if [ -n "$1" ]; then 
    

    如果没有引号,如果 $ 1 为空,则执行 [-n] ,这是真的*如果 $ 1 不为空,那么它显然如此。

    Without the quotes, if $1 is empty, you execute [ -n ], which is true*, and if $1 is not empty, then it's obviously true.

    *如果你给 [一个参数(不包括] ),它始终是真实的。 (顺便说一句,这是一个陷阱,许多新的用户分为时候,他们期望 [0] 是假的)。在这种情况下,单一的字符串是 -n

    * If you give [ a single argument (excluding ]), it is always true. (Incidentally, this is a pitfall that many new users fall into when they expect [ 0 ] to be false). In this case, the single string is -n.

    这篇关于针对-n选项测试中的bash脚本总是返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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