简体   繁体   English

bash 脚本 - 仅当不为空时才回显

[英]bash scripting - echo only if not empty

Is there an option or something I can use to encapsulate echo statements so that they don't print if the line is empty?是否有选项或我可以使用的东西来封装 echo 语句,以便它们在该行为空时不打印?

I was thinking something like:我在想这样的事情:

myecho(str){
  if [[ -z str ]]; then
    echo str
  fi
}

but I couldn't find how to pass parameters.但我找不到如何传递参数。

Arguments to functions are passed like arguments to scripts.函数的参数像参数一样传递给脚本。 Starting at $1 until $n$1$n

myecho(){
    if [ -n "$1" ] ; then
        echo "$@"
    fi
}

myecho ""
myecho "foo"

Using -n in a test you can verify that a string is not empty.在测试中使用-n可以验证字符串不为空。 Learn more about functions in bash: http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-8.html了解有关 bash 函数的更多信息: http : //tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-8.html

What about this?那这个呢?

[ -n "${STRING}" ] && echo ${STRING}

Or the complementer version:或者补充版本:

[ -z "${STRING}" ] || echo ${STRING}

Or you can do some "echo magic":或者你可以做一些“回声魔法”:

echo -en "Some prependig text before the empty string: \""
echo -n "${STRING}"
echo -e "\" and some postfix text..."
function echo2() {
   if [ -n "$1" ]
   then
      echo "$1"
   fi
}

man bash (Shell Parameter Expansion),如果str不为空或未设置,则回显${str}\\n

echo -n ${str:+$str\n} # ${str+$str\n} also works

This should work:这应该有效:

echo. 

or

echo. SOMEVARIABLE_WHICH_WILL_NOT_OUTPUT_IF_EMPTY

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM