samb
samb

Reputation: 1745

fix broken pipe with zsh

As suggested here https://www.howtogeek.com/howto/30184/10-ways-to-generate-a-random-password-from-the-command-line/ , I'm trying to generate random password with the following command :

< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c${1:-32};echo;

This works smooth in a bash shell, but gives the following warning/error message on zsh :

a8vuFvMzDcV4E-vbbkvfgi1Gf3KYtYiC[1] 40491 broken pipe tr -dc _A-Z-a-z-0-9 < /dev/urandom | 40492 done head -c${1:-32}

What could be the origin of this message and how could we adapt this to make it work on zsh ?

Upvotes: 0

Views: 1447

Answers (3)

samb
samb

Reputation: 1745

As discussed in the zsh mailing list https://www.zsh.org/mla/workers/2021/msg01171.html , this is the expected behavior when using the option setopt PRINT_EXIT_VALUE.

The solution to keep that option set, but not for that single command is to run it in a subshell as :

( < /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c 32; echo )

Upvotes: 1

samb
samb

Reputation: 1745

One workaround would be to use head to read /dev/urandom instead of tr, like so :

< /dev/urandom head -c 1000 | tr -dc _A-Z-a-z-0-9 | head -c 32; echo;

But there is no guarantee that I'll get a 32 chars random sequence. And increasing 1000 to 100000 leads to broken pipe again.

Upvotes: 0

Paul Zakharov
Paul Zakharov

Reputation: 547

Difficult to say, as it works perfectly for me on bash and zsh on two of my work-stations.

Probably it's not a so big deal as the problem that 1st process (urandom...) produce unlimited output that is written to 2nd process : "head -c${1:-32};echo;"

At the moment that the second process is over, the first still continue to write into the pipe and so give an error (as the pipe is closed by 2nd process).

It's explained better here :

https://superuser.com/questions/554855/how-can-i-fix-a-broken-pipe-error

There is also a solution in the same url, something like :

< /dev/urandom tr -dc _A-Z-a-z-0-9 | tail -n +1 | head -c${1:-32};echo;

But I could not check it as for me it works already well. Could you give a try ?

Upvotes: 0

Related Questions