Categories
FreeBSD Linux Mac

BASH: Capturing both the output and the exit code of a process

Of course I found an answer to this in a collection of Stack Overflow questions, but to make things easier for anybody who might stumble into this post (and mainly for Future Me), here’s the answer.

Seriously, don’t do this.

Basically I have a command that sometimes produces an error, but usually just re-running it produces the correct output. When it encounters an error, it dutifully sets its error code to something other than 0 (success). But how to I capture both the command’s output and its exit code? This way.

output=$(myCommandWhichSometimesDoesntWork)
exit_code=$? # This HAS to be exeuted right after the command above

So I made a little wrapper script that repeatedly calls the first one until it gets an answer, with a set maximum number of retries to avoid infinite loops.

#!/bin/bash
retries=0
max_retries=10 # Change this appropriately
 
# The "2> /dev/null" silences stderr redirecting it to /dev/null
# The command must be first executed outside of the while loop:
# bash does not have a do...while construct
output=$(myCommandWhichSometimesDoesntWork 2> /dev/null)
while [[ $? -gt 0 ]]
do
        ((retries++))
        if [[ retries -gt max_retries ]]
        then
                exit 1
        fi
 
        output=$(myCommandWhichSometimesDoesntWork 2> /dev/null)
done
 
echo $output
Categories
Linux Mac

Automatically download iOS firmwares

IPSW

Today I discovered that it takes quite a while to download an iOS IPSW, and when you need IPSWs, you are always in a hurry. So I made this little script that checks for a new release using icj.me’s API and downloads it. The comments in the script itself should make it pretty easy to use.

I added the script to my home server’s crontab, and scheduled it to run at 1 am every night, with a low bandwidth limit not to hog my connection.

Note: to use this on OS X you will have to either install wget (from sources, binaries, brew, ports, whatever) or edit the script to use curl.