Christian
Christian

Reputation: 3972

Why does this POSIX sh function set $? = 1

Very simple script but no idea why it sends an exit code of 1...

docker run --rm -it alpine
/ # apk update && apk add curl
...
...
/ # func() { RESPCODE=$(curl -sS -w "%{http_code}" -o /dev/null https://jsonplaceholder.typicode.com/todos/1); EXITCODE=$?; [ $EXITCODE -ne 0 ] && return 2; }
/ # func
/ # echo $?
1

Why does it not exit with zero code?!

Upvotes: 0

Views: 35

Answers (1)

KamilCuk
KamilCuk

Reputation: 141493

  • We assume curl suceeds.
  • EXITCODE=0
  • From https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html: The exit status of an AND list shall be the exit status of the last command that is executed in the list.
  • [ $EXITCODE -ne 0 ] exits with 1 exit status
  • return 2 does not execute
  • the last command in [ $EXITCODE -ne 0 ] && return 2 is [ $EXITCODE -ne 0 ]
  • [ $EXITCODE -ne 0 ] exited with 1 exit status
  • so the exit status of [ $EXITCODE -ne 0 ] && return 2 is 1
  • the last command in a function exited with 1 exit status.
  • the function exits with 1 exit status
  • echo $? outputs 1

Do not use && nor || as a condition. Use if.

Upvotes: 1

Related Questions