Bash Multiple Conditions in If Statement and Functions

我怕爱的太早我们不能终老 提交于 2020-01-22 02:39:08

问题


I'm trying to check if the number of arguments is one and if functions that I wrote in my script previously are true , but it does not work:

if [ $# -eq 1 && echo "$1" | lgt && echo "Invalid Length - $1" && echo "$1" | checking_another_function_etc ]; then
echo "some output" && exit 1

"lgt" is a function name.

I was trying to use (( [[ [ quotes, multiple if statements but it didn't work either. Maybe I should separate the number of arguments checking and functions with quotes, but I'm not sure how to do it. I'm wondering if it is even possible to pass echo command to if condition.

The thing is I need one echo statement after checking of all functions, but after each function I need its own echo statement.


回答1:


[ is an ordinary command (also spelled test); the [/] pair cannot simply surround a command list. Only the -eq expression is evaluated by [; the others are separate commands joined by the shell && operator.

if [ $# -eq 1 ] &&
   echo "$1" | lgt &&
   echo "Invalid Length - $1" &&
   echo "$1" | checking_another_function_etc; then
    echo "some output" && exit 1
fi

A possible separation of commands may provide what you expect:

if [ $# -ne 1 ]; then
    echo "Wrong number of arguments"
    exit 1
elif ! echo "$1" | lgt; then
    echo "Invalid length: $1"
    exit 1
elif echo "$1" | checking_another_function_etc; then
    echo "some output"
    exit 1
fi

It is rarely useful to make an echo command the LHS of the && operator, because its exit status is always 0.



来源:https://stackoverflow.com/questions/38677864/bash-multiple-conditions-in-if-statement-and-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!