Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

escape dollar sign in bashscript (which uses awk)

Tags:

bash

awk

I want to use awk in my bashscript, and this line clearly doesn't work:

line="foo bar"
echo $line | awk '{print $1}'

How do I escape $1, so it doesn't get replaced with the first argument of the script?

like image 253
One Two Three Avatar asked Aug 20 '13 20:08

One Two Three


People also ask

How do I escape the dollar sign in bash?

Escaping Special Characters The escape character, which in bash is backslash, can be used to ignore the meaning of several key characters. For instance, typically when the shell encounters a dollar sign followed by text, it tries to replace that with the contents of a variable.

Is awk '{ print $2?

awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output. xargs kill -${2:-'TERM'} takes the process IDs from the selected sidekiq processes and feeds them as arguments to a kill command.

What does dollar sign mean in awk?

You use a dollar sign (' $ ') to refer to a field in an awk program, followed by the number of the field you want. Thus, $1 refers to the first field, $2 to the second, and so on. (Unlike in the Unix shells, the field numbers are not limited to single digits.

What does AWK do in bash?

Awk is mostly used for pattern scanning and processing. It searches one or more files to see if they contain lines that matches with the specified patterns and then perform the associated actions. Awk is abbreviated from the names of the developers – Aho, Weinberger, and Kernighan.


1 Answers

Your script (with single quotes around the awk script) will work as expected:

$ cat script-single
#!/bin/bash
line="foo bar"
echo $line | awk '{print $1}'

$ ./script-single test
foo

The following, however, will break (the script will output an empty line):

$ cat script-double
#!/bin/bash
line="foo bar"
echo $line | awk "{print $1}"

$ ./script-double test
​

Notice the double quotes around the awk program.

Because the double quotes expand the $1 variable, the awk command will get the script {print test}, which prints the contents of the awk variable test (which is empty). Here's a script that shows that:

$ cat script-var
#!/bin/bash
line="foo bar"
echo $line | awk -v test=baz "{print $1}"

$ ./script-var test
baz

Related reading: Bash Reference Manual - Quoting and Shell Expansions

like image 94
cmbuckley Avatar answered Sep 22 '22 17:09

cmbuckley