1

shell script

#!/bin/bash

set -euo pipefail

for i in {1..1000}; do
    head -c 10000 /dev/urandom | tr -dc '0-1' | head -0 \
        && echo -n . \
        || { echo -e "\nNum $i, Unknown error!"; break; }
    sleep 0.1
done

Description

  • the only key command is
    head -c 10000 /dev/urandom | tr -dc '0-1' | head -0
    
  • this script broke after a few seconds
    .......................................
    Num 40, Unknown error!
    

Issue

  • why this script aborted?

1 Answer 1

1

First, to obtain exit code of a process, use $?. Replace your error reporting with:

echo -e "\nNum $i, error: $?"; break; 

This will show that when your script exits, a program exits with code 141.

This answer says code 141 means the process was killed with SIGPIPE.

Since you are asking head to read 0 lines, it could be exiting before the preceding programs have written anything to their output streams, resulting in an error.

One way of addressing this is to delay the final head slightly:

set -euo pipefail

for i in {1..1000}; do
    if head -c 10000 /dev/urandom | tr -dc '0-1' | (sleep 0 && head -0) ; then
    echo -n . 
    else
     echo -e "\nNum $i, error: $?"; break; 
     fi
    sleep 0.1
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.