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.
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityI 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.
Assuming that the code you posted is correct, what it does is very strange. It:
date 2
, which is not a valid invocation of date
and which will produce an error message, then&>
,$0
), erasing its existing contents.Because the way Bash reads in the script is to take one line at a time from the file, that results in it getting nonsense from the overwritten file and probably exiting (because the file has been truncated to shorter than the point this line appeared) or giving a syntax error (if the original was very short and part of the error is read in as the next line).
I can't think of a single legitimate use for that line, but as you say you've given it exactly as written, that is what it does.
Strictly speaking, it is possible to give another value to $0
and so execute this code non-destructively by invoking Bash with the -c
option: bash -c "$(<test.bash)" output-file
will put the error message into output-file
, but it's utterly perverse to do so.
Under bash
, if that command is in a script, the script file will be overwritten with an error message.
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'
The command, date 2&>$0
, is interpreted as follows:
The date
command is run with argument 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
.
Once the script file is overwritten, it is no longer a valid script and bash
will complain about the malformed commands.
bash
and POSIX shellsWith 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.
date 2>/dev/null
to produce an errorless date output, and failed spectaculary.