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 file
The 1><FILENAME>
tells the shell to redirect stdout
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 of date
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
redirects stderr
stream to that file also, it's a standard, POSIX compliant (which means Bourne-like shells other than bash
understand it)form. This is functionally equivalent to &>
bash-specific syntax. The order of specified redirections in shell is important, hence why this appears after 1>
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 blindly echo hello world
and hit Ctrl+D to exit afterwards):
$ bash --posix
bash-4.4$ exec 1>./mylog_`date '+%Y%m%d_%H%M%S'`.log 2>&1
$ cat ./mylog_20180424_010800.log
bash-4.4$ echo hello world
hello world
bash-4.4$ exit
Doing that piece by piece, reveals that bash
outputs prompt to stderr
stream and surprisingly along with anything I type:
bash-4.4$ exec 1> ./mylog.txt
bash-4.4$ echo Hello World
bash-4.4$ cat ./mylog.txt
cat: ./mylog.txt: input file is output file
bash-4.4$ exec 2>&1
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:
bash-4.4$ ksh
$ exec 1>./mylog 2>&1
echo hello askubuntu
bash-4.4$ cat ./mylog
$ hello askubuntu
$
bash-4.4$
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.
\\
s are most probably not supposed to be there. :) You didn't need to escape the ```s to keep them from being interpreted as inline code because you intented the text into a code block.... Seems like I'm one to talk... – JoL Apr 23 '18 at 17:48