Command-Line – How to Check if a Command Succeeded

command line

Is there any way to check if there is an error in executing a command?

Example :

test1=`sed -i "/:@/c connection.url=jdbc:oracle:thin:@$ip:1521:$dataBase" $search`
valid $test1

function valid () {
  if $test -eq 1; then
    echo "OK"
    else echo "ERROR" 
  fi
}

I already tried do that but it seems it isn't working. I don't how do that.

Best Answer

The return value is stored in $?. 0 indicates success, others indicates error.

some_command
if [ $? -eq 0 ]; then
    echo OK
else
    echo FAIL
fi

Like any other textual value, you can store it in a variable for future comparison:

some_command
retval=$?
do_something $retval
if [ $retval -ne 0 ]; then
    echo "Return code was not zero but $retval"
fi

For possible comparison operators, see man test.