Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiline assignment in bash

Tags:

bash

sh

In .cmd files on windows I do:

SET JARS=^
./lib/apache-mime4j-0.6.jar;^
./lib/apache-mime4j-0.6.jar;^
./lib/bsh-1.3.0.jar;^
./lib/cglib-nodep-2.1_3.jar;^
./lib/commons-codec-1.6.jar;^
./lib/commons-collections-3.2.1.jar;^
./lib/commons-exec-1.1.jar;^
./lib/commons-io-2.0.1.jar;^
./lib/commons-io-2.3.jar;

How can I do such multiline assignment in shell?

like image 485
Stepan Yakovenko Avatar asked Jun 27 '12 20:06

Stepan Yakovenko


People also ask

How do I create a multiline variable in Bash?

Although Bash has various escape characters, we only need to concern ourselves with \n (new line character). For example, if we have a multiline string in a script, we can use the \n character to create a new line where necessary.

How do I write multiple lines on a string in Bash?

To add multiple lines to a file with echo, use the -e option and separate each line with \n. When you use the -e option, it tells echo to evaluate backslash characters such as \n for new line. If you cat the file, you will realize that each entry is added on a new line immediately after the existing content.

What is ${ 2 in Bash?

$2 is the second command-line argument passed to the shell script or function.


2 Answers

So many ways to skin this cat.

JARS='
./lib/apache-mime4j-0.6.jar;
./lib/apache-mime4j-0.6.jar;
./lib/bsh-1.3.0.jar;
./lib/cglib-nodep-2.1_3.jar;
./lib/commons-codec-1.6.jar;
./lib/commons-collections-3.2.1.jar;
./lib/commons-exec-1.1.jar;
./lib/commons-io-2.0.1.jar;
./lib/commons-io-2.3.jar;
'

This gets you multiline input in a variable, per your question.

But if you're planning to USE these files in a shell script, you need to tell us how, so that we can come up with appropriate answers, rather than making us guess. For use in a shell script, files need to be delimited by something useful.

You asked, "How can I do such multiline assignment in shell", but the assignment in your example is actually a SINGLE line, with the ^ at the end of each input line negating the following newline (not escaping it, as another answer suggested).

My solution in this answer is multiline, but you'll need to explain more about what you need this for in order to determine what will be useful.

For example, if you need to step through a list of files that will be processed with the jar command, you might want to have something like:

#!/bin/sh

JARS='
./lib/apache-mime4j-0.6.jar
./lib/bsh-1.3.0.jar
...
'

set $JARS
for jarfile in "$@"; do
  jar xf "$jarfile" ...
done
like image 84
ghoti Avatar answered Sep 18 '22 15:09

ghoti


or alternatively

SOMEVAR=$( cat <<EOF
value1
value2
value3
value4
value5
EOF
)
like image 28
matcheek Avatar answered Sep 18 '22 15:09

matcheek