0

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?

  • Hard to tell exactly what you are wanting. You obviously know how to redirect as you are redirecting the error message to `stderr`. If you simply want to redirect `11` or `12`, you can just add an `echo 11 >> your.log` before `exit 11` and the same for the next function. You can declare your logfile variable at the top, e.g. `logfile="your.log"` and redirect to `$logfile` throughout your program. – David C. Rankin Sep 28 '20 at 05:02
  • What do you mean by "redirecting these exit codes"? – Ken Y-N Sep 28 '20 at 05:04
  • Does this answer your question? [In bash, how to store a return value in a variable?](https://stackoverflow.com/questions/15013481/in-bash-how-to-store-a-return-value-in-a-variable) – Ken Y-N Sep 28 '20 at 05:04
  • @jayculkin : What do you mean by _exit code of a **condition**_. A condition does not have an exit code. A command does. For instance, the `test` commands in your code have an exit code (either 0 or 1). – user1934428 Sep 28 '20 at 06:39

2 Answers2

0

Try this

echo "some data for the file" >> fileName

0

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
BeardOverflow
  • 938
  • 12
  • 15