What is the usage of $& in bash?

$& is not a single token/special variable, it is simply $ and &.

The command echo $& is treated as echo $ &, which echos a literal $ in the background.

$_ on the other hand is a special variable that expands to the last argument of the most recent command executed.


While the bash aspect has been covered, your question makes me think you've come across those variables in perl code.

$& and $_ are special variables in perl. And they are especially found in perl code called from the shell code.

$_ is the default variable many perl functions and operators work on. That variable is also the default variable set by input operators.

In:

perl -pe 'some-code' < some-input

Some-code is run for every line of some-input, with the line stored in $_, and the content of the $_ is printed after some-code has run.

The s/regex/replacement/ operator works on $_ by default. So you often find things like:

perl -pe 's/foo/bar/'

Which is short for:

perl -pe '$_ =~ s/foo/bar/'

(above, $_, as far as the shell is concerned is just part of a verbatim argument passed to the perl interpreter, it is not a shell variable. That verbatim argument is passed as perl expression (-e) to perl, and it's for perl that it is interpreted as a variable).

$& is another special perl variable that expands to whatever was matched by the last matching operator (m/.../ , s/.../.../...).

For instance:

$ echo foo | perl -lne '
    print "The last character in $_ is $&" if m/.$/'
The last character in foo is o

Or:

$ echo foo bar | perl -pe 's/[aeiou]+/<$&>/g'
f<oo> b<a>r

Tags:

Shell

Bash