I was looking into special parameters in bash. I am curious to know what is $& and how it is different from $_.

I see the following output when running the commands but could not locate the meaning as well.

k@Linux:~$ echo $&
[1] 12397
k@Linux:~$ echo $n

[1]+  Done                    echo $

$& 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.


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 "$_'s last character is $&" if m/.$/'
foo's last character is o


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

Providing & means you are going to run a particular command in the backend or as a job. So that is what the output of echo $& gives.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.