Lets see an example to perform Shell Redirection with Exec
In Unix shells exec is a builtin command. Here is how to check if a command is a shell builtin.
$? when evaluated by the shell results in the exit status of the previous command. A zero return value indicates that the command executed successfully. Execute the same set of commands above, but with
builtin ls and see what happens.
exec, it can redirect input and output of the current shell when executed without a command.
Standard output redirection:
$ exec > output # the standard output is redirected to file foo
$ ls # output of ls is written to file foo
Standard error redirection:
exec 2> error # the standard error is redirected to file error
$ ls no-such-file # output is written to file error
$ cat error > /dev/tty # prints contents of file error to terminal
exec is useful when writing a shell script that needs to log output of commands to different files.
$ exec 3>web.log # open web.log for writing using file descriptor 3
$ exec 4>uptime.log # open uptime.log for writing using file descriptor
$ curl google.com >& 3 # the '>& 3' syntax redirects standard out to fd 3
$ uptime >& 4
I hope this has been useful for you and I’d like to thank you for reading. If you like this article, please leave a helpful comment and share it with your friends.