Search code examples
bashshellif-statementfile-exists

Simple Shell if condition not working


if [ $? -ne 0 ]; then echo "error"; else echo "success"; fi

succeeds, and

if [ ! -f index.html ]; then echo "error"; else echo "success"; fi

succeeds, but for some reason

if [ ! -f index.html ] || [ $? -ne 0 ]; then echo "error"; else echo "success"; fi

fails.

In my case "index.html" exists and $? = 0


Solution

  • if [ ! -f index.html ] || [ $? -ne 0 ]
    

    The value of $? there reflects the exit code of [ ! -f index.html ]. Since index.html exists, that statement results in a nonzero exit code.

    Try instead:

    if [ $? -ne 0 ] || [ ! -f index.html ] ; then echo "error"; else echo "success"; fi
    

    Because [ $? -ne 0 ] is executed first, the value of $? will reflect the exit code of whatever the prior command was and not the result of [ ! -f index.html ].

    Another possibility is to put both tests into a single conditional expression:

    if [ ! -f index.html -o  $? -ne 0 ]; then echo "error"; else echo "success"; fi
    

    Because there is a now a single test expression, bash evaluates $? before the ! -f index.html test is run. Consequently, $? will be the exit code of whatever the prior command was.