0

Is it possible to do something like:

a="one"
b="two"
c="three"

str="
first=$a\n
second=$b\n
third=$c\n
"
printf $str

I've tried doing:

str=" \
first=$a\n \
second=$b\n \
third=$c\n \
"

Update: here is a series of attampts. The goal is to just be able to create a string on multiple lines. For instance, can be done in javascript and python.

lintest.sh

str1="
first line \n
second line \n
"

str2="
first line \n \
second line \n \
"

str3="
first line \
second line \
"

str4="
first line
second line
"

str5='first line\nsecond line\n'

a="first line"
b="second line"
str6="%s\n%s\n"

printf $str1
printf "\n"
printf $str2
printf "\n"
printf $str3
printf "\n"
printf $str4
printf "\n"
printf $str5
printf "\n"
printf $str6 \
"$a" \
"$b"

output:

balter@exalab3:~/lbalter$ bash lintest.sh
first
first
first
first
first
first line
second line
abalter
  • 9,663
  • 17
  • 90
  • 145

1 Answers1

1

You just need a \n wherever you want a newline and a \ wherever you want to continue (without a newline). What's screwing you up is printing the $variable: since Bash interpolates it into a command as if you'd just typed it there, you need to wrap it in quotes if you want to preserve the whitespace it contains.

a="one"
b="two"
c="three"

str="\
first=$a
second=$b
third=$c
"

printf "$str"
$ ./print.sh
first=one
second=two
third=three
$
Kristján
  • 18,165
  • 5
  • 50
  • 62