Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

My script is like this:

#!/bin/bash

mysql dbname -N -uroot -p -hhost -se "SELECT COUNTRY, COUNTRY_NAME FROM server ORDER BY COUNTRY"

output=$(mysql dbname -N -uroot -p -hhost -se "SELECT COUNTRY, COUNTRY_NAME FROM server ORDER BY COUNTRY")
echo $output

The result is like this:

Enter password: 
CN  China
CZ  Czech Republic
FI  Finland
JP  Japan
NL  Netherlands
RO  Romania
SG  Singapore
UA  Ukraine
US  United States
US  United States
US  United States
US  United States
Enter password: 
CN China CZ Czech Republic FI Finland JP Japan NL Netherlands RO Romania SG Singapore UA Ukraine US United States US United States US United States US United States

I want to set bash variable output to be the output of the mysql query, but the output variable seems to be good except all new lines were stripped away. My question is how to set the bash variable to be the mysql query result with each row in one line?

share|improve this question
up vote 5 down vote accepted

Instead of

echo $output

quote it ! Read about word splitting

echo "$output"

"Double quote" every literal that contains spaces/metacharacters and every expansion: "$var", "$(command "$var")", "${array[@]}", "a & b". Use 'single quotes' for code or literal $'s: 'Costs $5 US', ssh host 'echo "$HOSTNAME"'. See
http://mywiki.wooledge.org/Quotes
http://mywiki.wooledge.org/Arguments
http://wiki.bash-hackers.org/syntax/words

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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