LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   Why does this script (with pipefail) exit with nonzero status and how can I fix it? (https://www.linuxquestions.org/questions/linux-software-2/why-does-this-script-with-pipefail-exit-with-nonzero-status-and-how-can-i-fix-it-4175686571/)

DoorDaesh 12-09-2020 04:40 PM

Why does this script (with pipefail) exit with nonzero status and how can I fix it?
 
I enabled pipefail in my script for improved safety, but now there is one line that causes the script to fail, even though it's working as intended.

It's this line setting the value of rand_string:

Code:

$ set -o pipefail
$ rand_string=$(cat /dev/urandom | tr -cd 'a-f0-9' | head -c 12)
$ echo $?
# 141

I assume it's either the cat or tr command that's exiting with code 141. Which one is it? Why is it doing that? How can I make it stop?

shruggy 12-09-2020 05:02 PM

141 means 141-128=13=SIGPIPE Broken pipe: write to pipe with no readers.

This is how I would do it:
Code:

od -An -N6 -x /dev/urandom | tr -d ' '
Or
Code:

od -An -N6 -tx8 /dev/urandom | tail -c13
Or
Code:

hexdump -n6 -e'"%0x"' /dev/urandom
Or, if you have Vim installed:
Code:

xxd -l6 -p /dev/urandom

DoorDaesh 12-09-2020 05:26 PM

Does SIGPIPE occur because cat is still "printing" even after head takes what it needs?

shruggy 12-09-2020 05:33 PM

Yes, see this question.

DoorDaesh 12-09-2020 07:30 PM

Thanks for the solution. The od command is new to me, so I had to read up on it. I think I understand the purpose of most of those options now.
  • -An #Suppresses "line numbering"
  • -N6 #Amount to output
  • -tx8 #Controls output format and length of the "words" (8-byte hex)

Could you explain the purpose of -v? The manual says:
Code:

-v, --output-duplicates
      do not use * to mark line suppression

Does this mean that by default it will print an asterisk if a line is identical to the previous one?

shruggy 12-10-2020 03:33 AM

Yep. I amended my post and removed -v: it's not required here, as there's only one line of output anyway.

Also, see detailed explanation of pipefail behavior in BashPitfall #60.


All times are GMT -5. The time now is 04:36 AM.