0

I have a script which runs a mysql query on multiple database. i have it logging the query which was run to a file. When i pass in the query it contains new lines, but in the log file its is all on one line. Multi line queries are easier to read.

e.g:

$ sh run_query.sh 'CREATE TABLE`table` ( 
`id` int(10) unsigned NOT NULL AUTO_INCREMENT, 
`field1` int(10) unsigned NOT NULL, 
`field2` int(10) unsigned NOT NULL, 
PRIMARY KEY (`id`), 
 ENGINE=InnoDB;'

Is it possible for bash to keep the new lines in a passed variable?

3
  • The string itself is fine. The question is, how are you using (i.e., quoting) the parameter inside run_query.sh? Commented Sep 16, 2015 at 11:06
  • I am just using echo. e.g echo $sql >> logfile Commented Sep 16, 2015 at 16:18
  • I am simply echoing into a log file. but strange that a simple echo strips out the new lines. Is there a parameter to echo which will keep them? Commented Sep 16, 2015 at 16:19

2 Answers 2

1

In your comment, you mention using this code:

echo $sql >> logfile

However, this causes the shell to treat any newline character present in the value of $sql as whitespace to separate the string into multiple arguments for echo. You need to quote the expansion:

echo "$sql" >> logfile
Sign up to request clarification or add additional context in comments.

Comments

0

You can store multiline string in a variable first like this:

IFS= read -rd '' sql <<'EOF'
CREATE TABLE`table` ( 
`id` int(10) unsigned NOT NULL AUTO_INCREMENT, 
`field1` int(10) unsigned NOT NULL, 
`field2` int(10) unsigned NOT NULL, 
PRIMARY KEY (`id`), 
ENGINE=InnoDB;
EOF

Then pass it as:

sh run_query.sh "$sql"

2 Comments

There's no need to go through such contortions to set the value of sql. Newlines can be embedded in quotes as shown in the question.
Of course that may work but you understand very well a SQL can have single and double quotes and then this quoted string won't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.