Bash – What does `date 2&>$0` do

bashio-redirectionshell

I am looking at a co-workers shell code and I saw this:

date 2&>$0

I know what date does, but what's 2&>$0 doing?
He's out for a while, so I can't ask him what this part was about.

Best Answer

Summary

Under bash, if that command is in a script, the script file will be overwritten with an error message.

Example

Consider the script:

$ cat test.sh
date 2&>$0

Now, run the script:

$ bash test.sh
test.sh: line 2: unexpected EOF while looking for matching ``'
test.sh: line 3: syntax error: unexpected end of file

Observe the new contents of the script:

$ cat test.sh
date: invalid date `2'

Explanation

The command, date 2&>$0, is interpreted as follows:

  1. The date command is run with argument 2

  2. All output, both stdout and stderr, from the date command is redirected to the file $0. $0 is the name of the current script.

    The symbol > indicates redirection of, by default, stdout. As a bash extension, the symbol &> is a shortcut indication redirection of both stdout and stderr. Consequently, both stdout and stderr are redirected to the file $0.

  3. Once the script file is overwritten, it is no longer a valid script and bash will complain about the malformed commands.

Difference between bash and POSIX shells

With a simple POSIX shell, such as dash, the shortcut &> is not supported. Hence, the command date 2&>$0 will redirect only stdout to the file $0. In this case, that means that the script file is overwritten with an empty file while the date error message will appear on the terminal.

Related Question