How to specify a multi-line shell variable?

I wrote a request:

function print_ui_hosts { local sql = "select ........." print_sql "$ sql" } 

local sql is a very long string. The request is not formatted. How can I split a string into multiple lines?

+72
bash shell
Mar 15 '13 at 9:58
source share
5 answers

Use read with heredoc as shown below:

 read -d '' sql << EOF select c1, c2 from foo where c1='something' EOF echo "$sql" 
+91
Mar 15 '13 at 10:04 on
source share

just insert a new line if necessary

 sql=" SELECT c1, c2 from Table1, Table2 where ... " 

the shell will look for a closing quote

+109
Mar 15 '13 at 10:07
source share

I would like to give one more answer, while others will be sufficient in most cases.

I wanted to write a line along several lines, but its contents should be single-line.

 sql=" \ SELECT c1, c2 \ from Table1, ${TABLE2} \ where ... \ " 

I apologize if this is a little off topic (I don't need this for SQL). However, this message appears among the first results when searching for multi-line shell variables, and an additional answer seems appropriate.

+41
May 22 '14 at 8:24
source share

Thanks to dimo414, answering a similar question , this shows how its excellent solution works, and shows that you can easily use quotes and variables in the text:

Output example

 $ ./test.sh The text from the example function is: Welcome dev: Would you "like" to know how many 'files' there are in /tmp? There are " 38" files in /tmp, according to the "wc" command 

test.sh

 #!/bin/bash function text1() { COUNT=$(\ls /tmp | wc -l) cat <<EOF $1 Would you "like" to know how many 'files' there are in /tmp? There are "$COUNT" files in /tmp, according to the "wc" command EOF } function main() { OUT=$(text1 "Welcome dev:") echo "The text from the example function is: $OUT" } main 
+5
Feb 22 '16 at 15:44
source share

read does not export the variable (which is very convenient in most cases). Here, an alternative that can be exported to a single command can save or discard line breaks and allows you to mix citation styles if necessary. Works for bash and zsh.

 oneLine=$(printf %s \ a \ " b " \ $'\tc\t' \ 'd ' \ ) multiLine=$(printf '%s\n' \ a \ " b " \ $'\tc\t' \ 'd ' \ ) 

I admit that the need for quoting makes this ugly for SQL, but it answers the question (more general) in the header.

I use it like that

 export LS_COLORS=$(printf %s \ ':*rc=36:*.ini=36:*.inf=36:*.cfg=36:*~=33:*.bak=33:*$=33' \ ... ':bd=40;33;1:cd=40;33;1:or=1;31:mi=31:ex=00') 

in a file obtained from my .bashrc and .zshrc .

+2
Oct 18 '16 at 8:38
source share



All Articles