Skip to content
Advertisement

How to redirect specific exit code into a file in bash [closed]

I currendtly have two if statements, each with a different exit code. How can I store these exit codes into a file?

if [ !condition 1 ];then
   echo "Please enter valid name" 1>&2
   exit 11
fi

if [ !condition 2 ];then
   echo "Please enter valid digits" 1>&2
   exit 12
fi

Is there anyway to redirect these specific exit codes into a file in bash?

Advertisement

Answer

You can capture the exit code using the $? variable:

#!/bin/bash

ls -l
exit_code=$?

echo "Exit code was: ${exit_code}" >> ~/myfile

if [ ${exit_code} -eq 0 ]
then
  echo "Success"
else
  echo "Error code: ${exit_code}"
fi
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement