问题
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