I'm trying to understand what the below piece of shell script is doing. I know that exec without any arguments redirect the output of the current shell but am not able to understand what the below command does:
exec 1>/var/opt/log/my_logs/MYPROG_`date '+%Y%m%d_%H%M%S'`.log 2>&1
There's actually 4 important bits of information that are happening:
The
exec
built-in is used to redirect all output for command-line session to a fileThe
1><FILENAME>
tells the shell to redirectstdout
standard stream, i.e. normal non-error output of commands will go to<FILENAME>
. The>
will create if<FILENAME>
doesn't exist or truncate if<FILENAME>
already exists.The redirected filename is created via added backticks with
date '+%Y%m%d_%H%M%S'
command. Backticks are form of Command Substitution and are functionally equivalent to$(date '+%Y%m%d_%H%M%S')
form, and nowadays$(...)
is preferred for readability and because this form can be easily nested (i.e., have multiple levels). So output ofdate
with the specified format'+%Y%m%d_%H%M%S'
will create filename that is timestamped. If your command ran on 2018, July, 4th, 4:20:20 the output will be/var/opt/log/my_logs/MYPROG_20180704_042020.log
.2>&1
redirectsstderr
stream to that file also, it's a standard, POSIX compliant (which means Bourne-like shells other thanbash
understand it)form. This is functionally equivalent to&>
bash-specific syntax. The order of specified redirections in shell is important, hence why this appears after1>
redirection.In conclusion, there should be no output from this command itself. It should only rewire two output streams of all successive commands to go into the file you specified.
Interestingly enough, with this command my
bash 4.4
outputs everything to file, and that includes the prompt and anything I type (so here I had to type blindlyecho hello world
and hit Ctrl+D to exit afterwards):Doing that piece by piece, reveals that
bash
outputs prompt tostderr
stream and surprisingly along with anything I type:In case of
ksh
same thing happens, but I can see what is being typed, only the prompt goes to file, i.e. stdin isn't redirected:So here we can kinda see that shells can choose to output the prompt
PS1
also to one of the standard streams, so that gets included into a file.