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

有帮助吗?

解决方案

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.

其他提示

Try this instead:

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

Every command you execute changes $?. It is best to store this immediately in a new variable and then check it at your leisure.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top