0

I originally coded something to fetch a file via wget like this:

local wget_output=$(wget -O "${TEMP_FILE}"  "$REQUEST_URL" 2>&1)
local wget_success=$?
if [[ $wget_success -eq 0 ]]; then

so that the 'then' clause would only execute if the wget was successful. However, it executed every time (ie. when the requested file was not on the server.) This code works functionally correct:

wget_output=$(wget -O "${TEMP_FILE}"  "$REQUEST_URL" 2>&1)
local wget_success=$?
if [[ $wget_success -eq 0 ]]; then

The only difference is the removal of the first local. Can anyone explain why?

JoeG
  • 7,191
  • 10
  • 60
  • 105
  • 1
    It's not that the variable is local, it's that you're declaring it local *on the same line*, so the exit status of `local`, rather than the exit status of your command substitution, is in `$?`. Give me a minute and I'll find a dupe for this one. – Charles Duffy Jun 13 '17 at 17:41
  • Duplicate of [Why does “local” sweep the return code of a command?](https://stackoverflow.com/questions/4421257/why-does-local-sweep-the-return-code-of-a-command) – Gordon Davisson Jun 13 '17 at 17:42
  • Declare your locals *before* you assign to them: `local wget_output; wget_output=$(wget ...)` will avoid this issue. – Charles Duffy Jun 13 '17 at 17:43
  • btw, as a stylistic matter, I'd consider `if wget_output=$(wget ...); then ...` rather than capturing `wget_success` at all. If you need to distinguish between specific error codes, by contrast, then you can capture `$?` in the `else` clause. – Charles Duffy Jun 13 '17 at 17:45
  • Sorry about the dupe - I was totally lost on this one and could not determine the correct search parameters! – JoeG Jun 13 '17 at 17:45
  • @JoeG That's often a problem with bash. [shellcheck](http://shellcheck.net) would have pointed out [this issue](https://github.com/koalaman/shellcheck/wiki/SC2155). – that other guy Jun 13 '17 at 17:59
  • Installed ShellCheck, now officially in the toolbox - thank you! – JoeG Jun 13 '17 at 19:22

0 Answers0