I have this flat file database(ff_servers.db) with following contents: Alaska   hp Colorado dell hawaii   hp

From command line, I could run:

awk "BEGIN{IGNORECASE=1;}/alaska/ {print $NF}" ff_servers.db`

and I would get


However, from a bash script, I'm having problems with "$NF" Here's the dump of that script:

machine_type=`awk "BEGIN{IGNORECASE=1;}/${server_name}/ {print \$NF}" ff_servers.db`
awk "BEGIN{IGNORECASE=1;}/${server_name}/ {print $NF}" ff_servers.db
++ awk 'BEGIN{IGNORECASE=1;}/colorado/ {print }' ff_servers.db
+ target_arch='   Colorado           dell'

So obviously, $NF is not being translated properly. Where am I doing wrong?

  • Use the standard "$()" format to ensure more conventional quoting behaviour. – orion Feb 12 '15 at 18:40

Bash expands variables (such as identifiers beginning with $) within double quotes ".

Although this should have also been a problem when doing this interactively from the commmand line. Bash will try expand "$NF", if the variable NF isn't defined then bash will expand this to the empty string.

Usually you can use single quotes ' so that $NF will not be expanded by bash.

However since you want ${server_name} to expand, you can try double escaping

machine_type=`awk "BEGIN{IGNORECASE=1;}/${server_name}/ {print \\$NF}" ff_servers.db`

You could also try using string concatenation, the difference is mostly stylistic.

machine_type=`awk 'BEGIN{IGNORECASE=1;}/'${server_name}'/{print $NF}' ff_servers.db`

This works as bash will concatenate adjacent strings together.

  • thanks for the help. I figured out the answer myself as I was fiddling with my script. As I had the need for $server_name to be a variable, I had this instead: machine_type=awk 'BEGIN{IGNORECASE=1;}/'${server_name}'/ {print $NF}' ff_servers.db` `coz if I would leave it as you suggested, $server_name would then be interpreted not as a variable but a constant with $ sign. – icasimpan Dec 27 '12 at 7:44
  • I was just in the process of writing about string concatenation as a possible solution :) – cjh Dec 27 '12 at 7:48
  • 2
    I prefer to not mess up the code with escaping: machine_type=$(awk -vserver_name="$server_name" 'BEGIN{IGNORECASE=1}$0~server_name{print $NF}' ff_servers.db). – manatwork Dec 27 '12 at 7:51
  • @manatwork, can you clarify your solution please? I can't seem to make it work. Maybe on a separate answer instead of a comment as it breaks some statements – icasimpan Dec 27 '12 at 8:06
  • 1
    See here: pastebin.com/LPsLG4xz What kind of awk you use? – manatwork Dec 27 '12 at 8:17

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.