How can I use && with my own functions?

Running this output prints both statements

#!/bin/bash
echo "Hello" && echo "World"

However, when you run this file, only "Hello" is displayed.

#!/bin/bash
message() {
  echo "Hello"
  return 1
}
message && echo "World"

Why does this not work and how can I change my script so that it does?

+3
source share
5 answers

An exit value of 0 means success, and something else means failure. and the && operator does not execute the right side if the left side fails (that is, if it returns a nonzero value)

So change return 1toreturn 0

+7
source

return 1(or anything else that is not 0) means falsebefore bash, which means that the second command will not be called.

return 0 ( true) (, || ;.)

, bash , && || " " , " " ". a && b " b , a ", " " ( true 0, false 1), , .

+5

bash 1 .

return 0

+5

& & , , 0

+4

return message().

+1

All Articles