setop icon indicating copy to clipboard operation
setop copied to clipboard

Use exit codes instead of writing `0` and `1`

Open andlrc opened this issue 9 years ago • 2 comments

This will enable usage like this:

setop is-empty < my_file && echo "File is empty..." || echo "File is NOT empty"

if setop is-empty < my_file; then
  echo "Empty"
fi

andlrc avatar Feb 16 '16 23:02 andlrc

Hey @ginkoms

Thanks for your contribution! I agree with you in that this sort of usage would be really great when used from within other scripts.

However, I'm sort of worried by the fact that nothing gets displayed on the console anymore when it's run as a standalone program, unless you explicitly print things based on the exit status. This worries me because this set of commands is directed mostly at people who're really new to bash (as I was, not so long ago when I started using these functions for the first time).

Can we look for some sort of a middle ground here? Let me know if I'm missing something obvious.

cdax avatar Feb 18 '16 18:02 cdax

@cdax You can check to see if stdin/ stdout is interactive:

# if stdout is interactive then print a truly value (1). If not then exit successfully
[ -t 1 ] && echo 1 || exit 0

However using -t can have unexpected behavior:

But, as John points out: if [ -t 0 ] works ... when you're logged in locally but fails when you invoke the command remotely via ssh. So for a true test you also have to test for a socket. if [[ -t "$fd" || -p /dev/stdin ]]

Source: http://www.tldp.org/LDP/abs/html/intandnonint.html

However stdin and stdout can both be interactive while you are not interested in the output:

setop is-active <&0 >&1

Alternative you both write output and exit with a status code:

echo 1
exit 0

Then it can still be used in an if-statement like this:

if setop is-empty > /dev/null < file; then
  echo "The file is indeed empty"
fi

What is happening is that the stdout output is redirected to /dev/null so no output is printed, and the exit code is interpreted by the if-statement.

I hope this gives you an idea of your alternatives.

I would suggest always using exit codes, and then either: Always printing 1/0 or alternative only print when interactive

andlrc avatar Feb 18 '16 22:02 andlrc