I saw a bash script which had exec 1>&2
command in a function. Something like:
function example()
{
exec 1>&2
cat <<EOT
Script requires at least one parameter.
EOT
exit 1
}
As I understand, exec 1>&2
means that everything from this point one will be directed to stderr. Is this some sort of fixed behaviour of exec one needs to know by heart or is there some good explanation behind this? I mean as I understand, exec in Bash script just invokes a command taking the same PID which the Bash script had and once the command is finished, the PID is killed. 1>&2 isn't a command. Could somebody explain the details(especially the why question) behind the exec 1>&2
command?
On Unix-like operating systems, exec is a builtin command of the Bash shell. It lets you execute a command that completely replaces the current process. The current shell process is destroyed, and entirely replaced by the command you specify.
- 1 means the first parameter passed to the function ( $1 or ${1} ) - # means the index of $1 , which, since $1 is an associative array, makes # the keys of $1.
The exec command is a powerful tool for manipulating file-descriptors (FD), creating output and error logging within scripts with a minimal change. In Linux, by default, file descriptor 0 is stdin (the standard input), 1 is stdout (the standard output), and 2 is stderr (the standard error).
There are no Booleans in Bash. However, we can define the shell variable having value as 0 (“ False “) or 1 (“ True “) as per our needs.
The why is an accident of history, there isn't a great reason for it.
The redirection operators are applied to any program (for example, cat
) and the >&
form was added to express the "duplicate file descriptor 1 from 2" because it was useful. The >&
syntax probably was used because they were running out of special characters and >&
was nonsense given the basic meaning of &
and >
(but don't quote me on that). This stuff all dates back to the early Bourne shell around 1977.
Why exec
plus a redirection to alter the input and output of the current shell? Probably because there was already a meaning for the null command > path
which had the same effect as cat /dev/null > path
but was easier to type, and when your teletype ran at 10 characters per second at best, that mattered. So the exec
built-in was then overloaded: with no arguments, it applied the redirection operations to itself.
Since bash tries to adhere to Bourne shell convention as much as possible, you get these antiquities which, as you suspect, you just have to remember especially if you are trying to impress other members of the appropriate sex (i.e. "chicks dig a guy who knows his i/o redirection arcana").
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