Shellcheck: SC2181: what about capturing output?

Created on 23 Nov 2016  路  6Comments  路  Source: koalaman/shellcheck

https://github.com/koalaman/shellcheck/wiki/SC2181 seems to be a new warning.

I read through it, and I was wondering what I should do about cases where I want to capture both the output and the exit code, and then branch based on the exit code?

Most helpful comment

if  var=$( somecmd )
then echo SomeCmd succeeded with output "$var"
else echo SomeCmd failed with status $?
fi

On Wed, 23 Nov 2016, Jordan Harband wrote:

Date: Thu, 24 Nov 2016 05:30:52
From: Jordan Harband notifications@github.com
Reply-To: koalaman/shellcheck
[email protected]>
To: koalaman/shellcheck shellcheck@noreply.github.com
Subject: [koalaman/shellcheck] SC2181: what about capturing output? (#782)

https://github.com/koalaman/shellcheck/wiki/SC2181 seems to be a new warning.

I read through it, and I was wondering what I should do about cases where I want to capture both the output and the exit code, and then branch based on the exit code?

All 6 comments

if  var=$( somecmd )
then echo SomeCmd succeeded with output "$var"
else echo SomeCmd failed with status $?
fi

On Wed, 23 Nov 2016, Jordan Harband wrote:

Date: Thu, 24 Nov 2016 05:30:52
From: Jordan Harband notifications@github.com
Reply-To: koalaman/shellcheck
[email protected]>
To: koalaman/shellcheck shellcheck@noreply.github.com
Subject: [koalaman/shellcheck] SC2181: what about capturing output? (#782)

https://github.com/koalaman/shellcheck/wiki/SC2181 seems to be a new warning.

I read through it, and I was wondering what I should do about cases where I want to capture both the output and the exit code, and then branch based on the exit code?

Like kurahaupo says, Assignments like var=$(cmd) have the exit code of cmd so you can use it directly in if statements.

The code in the issue you linked to doesn't use $? for anything other than the branch itself, but if you wanted to do that, it would be better to assign it to another variable since branching based on it will also change it.

Feel free to reopen with any comments or questions!

Thanks, appreciate the help!

(It'd be helpful to add this to the documentation for the error)

I want to echo the sentiment of adding this to the relevant documentation.

I came here because I had

   commit_dates=$(dates "$path")
   [ $? -gt 0 ] && exit 255

It worked nicely to change it to

      if ! commit_dates=$(dates "$path")
      then
          exit 255
      fi

Done.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ymkjp picture ymkjp  路  3Comments

ghost picture ghost  路  4Comments

erwinkramer picture erwinkramer  路  5Comments

arth1 picture arth1  路  4Comments

nathaniel112 picture nathaniel112  路  4Comments