Home > Software engineering >  How to execute some commands on non zero exit code?
How to execute some commands on non zero exit code?

Time:06-28

I am running the following command:

OLDIFS=$IFS
IFS=$'\n'
for i in $(find $HOME/test -maxdepth 1 -type f); do
    if [ $? -eq 0 ]; then
        telegram-upload --to 12345 --directories recursive --large-files split --caption '{file_name}' $i &&
            rm $i
    fi
done
IFS=$OLDIFS

If the telegram upload command exits with a non zero code I intend to do the following:

rm somefile && wget someurl && rerun the whole command

How do I go about doing something like this?

CodePudding user response:

I believe you can capture the exit code as follows:

exit_code=$(telegram-upload --to 12345 ...)

From here, you can use the variable $exit_code as a regular variable,
like if [ $exit_code -eq 0 ]; then).

CodePudding user response:

It's straightforward: Do an endless loop, which you break out once you succeed:

for i in $(find $HOME/test -maxdepth 1 -type f)
do
  while true
  do
    if telegram-upload --to 12345 --directories recursive --large-files split --caption '{file_name}' $i
    then
      break
    else
      rm somefile && wget someurl
    fi
  done
done

UPDATE : For completeness, I added the loop over the files as well. Note that your approach of looping over the files will fail, if you have files where the name contains white space. However this is already a problem in your own approach and not part of the question, so I don't discuss this here.

  • Related