Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  • 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading