Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a workaround for this Broken Pipe error?

Tags:

bash

pipe

When I run the following script:

#!/bin/bash
cat /dev/urandom | tr -dc '[:graph:]' | head -c 64

(which is supposed to print 64 random characters and it does)

I get the following output:

Kn5Thh'H]F2NMG3^2(T*GdH]C+|Y0uj%C?LGFo=9d9o%vcP9k~6u~Q&exr`RuQv{./myScript: line 2: 21677 Broken Pipe             cat /dev/urandom
     21678                       | tr -dc '[:graph:]'
     21679 Done                    | head -c 64

Why am I getting the Broken Pipe error? Is it because cat doesn't finish printing but head is already done, so it sends a SIGPIPE?

How do I avoid this?

like image 597
bp99 Avatar asked Feb 10 '18 21:02

bp99


1 Answers

Well, this behavior seems to depend on two settings:

  1. compile-time option DONT_REPORT_SIGPIPE hasn't been set in your bash version (cf config-top.h)
  2. bash option set -o pipefail is in effect in your environment

Nonetheless, you can create a subshell with parentheses, and redirect the standard-error of the subshell into /dev/null:

(tr -dc '[[:graph:]]' </dev/urandom | head -c64) 2>/dev/null

--- Before the last edit this answer looked like this: ---

tr -dc '[[:graph:]]' </dev/urandom 2>/dev/null | head -c64
like image 151
Lorinczy Zsigmond Avatar answered Sep 28 '22 04:09

Lorinczy Zsigmond