Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pipe string with newline to command in bash?

Tags:

bash

I am trying to pass in a string containing a newline to a PHP script via BASH.

#!/bin/bash

REPOS="$1"
REV="$2"

message=$(svnlook log $REPOS -r $REV)
changed=$(svnlook changed $REPOS -r $REV)

/usr/bin/php -q /home/chad/www/mantis.localhost/scripts/checkin.php <<< "${message}\n${changed}"

When I do this, I see the literal "\n" rather than the escaped newline:

blah blah issue 0000002.\nU app/controllers/application_controller.rb

Any ideas how to translate '\n' to a literal newline?

By the way: what does <<< do in bash? I know < passes in a file...

like image 939
Chad Johnson Avatar asked Aug 13 '10 13:08

Chad Johnson


People also ask

How do I add a new line to a string in bash?

Printing Newline in Bash The most common way is to use the echo command. However, the printf command also works fine. Using the backslash character for newline “\n” is the conventional way. However, it's also possible to denote newlines using the “$” sign.

How do I break a line in bash?

Linux Files, Users, and Shell Customization with Bash If you want to break up a command so that it fits on more than one line, use a backslash (\) as the last character on the line. Bash will print the continuation prompt, usually a >, to indicate that this is a continuation of the previous line.

What does $() mean in bash?

Again, $() is a command substitution which means that it “reassigns the output of a command or even multiple commands; it literally plugs the command output into another context” (Source).

Can you pipe in a bash script?

A pipe in Bash takes the standard output of one process and passes it as standard input into another process. Bash scripts support positional arguments that can be passed in at the command line.


2 Answers

try

echo -e "${message}\n${changed}" | /usr/bin/php -q /home/chad/www/mantis.localhost/scripts/checkin.php 

where -e enables interpretation of backslash escapes (according to man echo)

Note that this will also interpret backslash escapes which you potentially have in ${message} and in ${changed}.


From the bash manual: Here Strings

A variant of here documents, the format is:

<<<word

The word is expanded and supplied to the command on its standard input.

So I'd say

the_cmd <<< word

is equivalent to

echo word | the_cmd
like image 119
Andre Holzner Avatar answered Oct 06 '22 17:10

Andre Holzner


newline=$'\n'
... <<< "${message}${newline}${changed}"

The <<< is called a "here string". It's a one line version of the "here doc" that doesn't require a delimiter such as "EOF". This is a here document version:

... <<EOF
${message}${newline}${changed}
EOF
like image 36
Dennis Williamson Avatar answered Oct 06 '22 18:10

Dennis Williamson