bash 用换行符管道字符串到bash中的命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3477429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pipe string with newline to command in bash?
提问by Chad Johnson
I am trying to pass in a string containing a newline to a PHP script via BASH.
我正在尝试通过 BASH 将包含换行符的字符串传递给 PHP 脚本。
#!/bin/bash
REPOS=""
REV=""
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:
当我这样做时,我看到的是文字 "\n" 而不是转义的换行符:
blah blah issue 0000002.\nU app/controllers/application_controller.rb
Any ideas how to translate '\n' to a literal newline?
任何想法如何将 '\n' 转换为文字换行符?
By the way: what does <<< do in bash? I know < passes in a file...
顺便说一句:<<< 在 bash 中做什么?我知道 < 传入一个文件...
回答by Andre Holzner
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
)
其中 -e 启用反斜杠转义的解释(根据man echo
)
Note that this will also interpret backslash escapes which you potentially have in ${message}
and in ${changed}
.
请注意,这也将解释您可能${message}
在${changed}
.
From the bash manual: Here Strings
来自 bash 手册: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
回答by Paused until further notice.
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:
在<<<
被称为“这里字符串”。它是“here doc”的单行版本,不需要诸如“EOF”之类的分隔符。这是这里的文档版本:
... <<EOF
${message}${newline}${changed}
EOF
回答by Andre Holzner
in order to avoid interpretation of potential escape sequences in ${message}
and ${changed}
, try concatenating the strings in a subshell (a newline is appended after each echo
unless you specify the -n
option):
为了避免潜在的转义序列的解释中${message}
,并${changed}
尝试在子shell串接字符串(一个换行符后每个附加echo
除非你指定-n
选项):
( echo "${message}" ; echo "${changed}" ) | /usr/bin/php -q /home/chad/www/mantis.localhost/scripts/checkin.php
The parentheses execute the commands in a subshell (if no parentheses were given, only the output of the second echo would be piped into your php program).
括号在子 shell 中执行命令(如果没有给出括号,则只有第二个 echo 的输出将通过管道传输到您的 php 程序中)。