I have a shell pipeline for generating 10 characters password at random:
cat /dev/urandom | base64 | head -c 10
My question is cat /dev/urandom | base64
is an infinite output stream which will not exit by itself. But why does appending head -c 10
make the whole pipeline exit? I assume cat
, base64
and head
are 3 separated processes, how can head
make the cat
process exit?
Just like && , || is a bash control operator: && means execute the statement which follows only if the preceding statement executed successfully (returned exit code zero). || means execute the statement which follows only if the preceding statement failed (returned a non-zero exit code).
The PIPESTATUS environment variable in Bash comes to our rescue for getting the exit status of each command in a pipeline. $ PIPESTATUS is an array. It stores the exit status of each command in the pipeline: $ hello_world.sh 5 | grep "Hello World" | grep "Hello Universe" $ echo ${PIPESTATUS[@]} 5 0 1.
In Linux, an exit code indicates the response from the command or a script after execution. It ranges from 0 to 255. The exit codes help us determine whether a process ran: Successfully.
A pipe in Bash takes the standard output of one process and passes it as standard input into another process. Bash scripts support positional arguments that can be passed in at the command line.
head
closes the input file after reading the required amount. when a pipe is closed from one side, the other side gets write errors; this causes base64
to close, which in turn causes cat
to close.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With