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?!
>Solution :
- We assume
curlsuceeds. 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 with1exit statusreturn 2does not execute- the last command in
[ $EXITCODE -ne 0 ] && return 2is[ $EXITCODE -ne 0 ] [ $EXITCODE -ne 0 ]exited with1exit status- so the exit status of
[ $EXITCODE -ne 0 ] && return 2is 1 - the last command in a function exited with
1exit status. - the function exits with
1exit status echo $?outputs1
Do not use && nor || as a condition. Use if.