Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell bash not to expand $_ variable?

Tags:

bash

perl

I want to use some perl line, like this:

perl -pe "$_=~s///e"

The problem is, bash keeps expanding the "$_" variable. I could put the perl expression into single quotes, but that would prevent me from adding some variables into a script.

Is there a way stop bash from expanding "$_" variable?

like image 407
Rogach Avatar asked Mar 18 '12 18:03

Rogach


People also ask

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

What does $() mean bash?

Example of command substitution using $() in Linux: Again, $() is a command substitution which means that it “reassigns the output of a command or even multiple commands; it literally plugs the command output into another context” (Source).

What does $_ mean in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails. $@

Does bash ignore whitespace?

Bash uses whitespace to determine where words begin and end. The first word is the command name and additional words become arguments to that command.


2 Answers

perl -pe '$_=~s///e'

or

perl -pe "\$_=~s///e"
like image 131
j13r Avatar answered Sep 28 '22 05:09

j13r


First off: You know that you can use $ENV{myvariable} to access environment variables, right? And that you do not need to specify $_ when using m//, s/// and tr///?

Furthermore, if you want to pass variables to perl, there are other ways of doing that besides trying to interpolate shell variables into your perl code.

perl -we 'my ($var1, $var2, $var3) = @ARGV;' "$MYFOO" "$BAR" "$baz"

If your shell variables do not contain whitespace, you can dispense with the quoting.

Now, if you want to use the -p or -n switches, there are ways around that too.

perl -pwe 'BEGIN { my $var1 = shift; my $var2 = shift } #code goes here'
    "$MYFOO" "$BAR" file1 file2 

Using shift in a BEGIN statement will remove variables from @ARGV so that they are not used by the implicit while loop of the -p and -n switches.

like image 42
TLP Avatar answered Sep 28 '22 05:09

TLP