0

Hi I am new to shell script. I have a command like this.

awk 'BEGIN{ print "Query" }
 /Executing command\(queryId/{ sub(/.*queryId=[^[:space:]]+: /,""); q=$0 }
 /s3:\/\//{ print q }' OFS=',' hive-server2.log

It prints the output perfectly like this.

select * from claimpfphdr limit 5
select * from claimpfphdr limit 5
select * from claimpfphdr limit 5

But When I use the same command to add the result in variable, Like this.

a=$(awk 'BEGIN{ print "Query" }
 /Executing command\(queryId/{ sub(/.*queryId=[^[:space:]]+: /,""); q=$0 }
 /s3:\/\//{ print q }' OFS=',' hive-server2.log)

It adds unwanted values.This is the output of the above shell variable.

echo $a
Query select License.txt LogMX-64.exe LogMX.app LogMX.bat LogMX.exe Log_Copyier.sh Readme.txt config help hive-server2.log jar lib logmx.command logmx.sht1.sh test.txt test_result.txt from pfeevent limit 

Any help will be appreciated.

Arun Kumar
  • 35
  • 5
  • 1
    what output do you get if you try `echo "$a"` – Sundeep Jan 23 '18 at 04:35
  • I mentioned above...Query select License.txt LogMX-64.exe LogMX.app LogMX.bat LogMX.exe L – Arun Kumar Jan 23 '18 at 04:35
  • read my comment again.... – Sundeep Jan 23 '18 at 04:36
  • Yeah now it prints correct values. – Arun Kumar Jan 23 '18 at 04:37
  • Thanks...Sundeep – Arun Kumar Jan 23 '18 at 04:38
  • Possible duplicate of [When to wrap quotes around a shell variable?](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable) – Sundeep Jan 23 '18 at 04:39
  • 1
    When you expand a variable (e.g. `$a`) without putting double-quotes around it, its value is subject to word splitting and glob (wildcard) expansion. You almost never want this, so double-quotes should be the norm. In this case, you're getting hit by both: glob expansion replaces each "*" with a list of files in the current directory, and word splitting looses track of where the line breaks are. – Gordon Davisson Jan 23 '18 at 04:41

1 Answers1

1

Use echo "$a" to preserve the new lines for a variable. Double-quoted version of the variable (echo "$variable") is to preserve internal spacing of the value exactly as it is represented in the variable newlines, tabs, multiple blanks and all. On the other hand unquoted version (echo $variable) replaces each sequence of one or more blanks, tabs and newlines with a single space.

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93