<分区>
如何在 Bash CLI 中传递包含 LF 字符的参数?类似于:myprog foo\nbar
我试过这个:
myprog `printf 'foo\nbar'`
myprog foo\nbar
我用这个 bash 程序来测试结果:
#myprog
echo $*
还有 node.js 程序
#!/usr/bin/env node
console.log(process.argv[2])
它不起作用。
<分区>
如何在 Bash CLI 中传递包含 LF 字符的参数?类似于:myprog foo\nbar
我试过这个:
myprog `printf 'foo\nbar'`
myprog foo\nbar
我用这个 bash 程序来测试结果:
#myprog
echo $*
还有 node.js 程序
#!/usr/bin/env node
console.log(process.argv[2])
它不起作用。
最佳答案
在bash
使用 ANSI C like strings , 与 $'...'
符号如下。当您想将特殊字符作为参数传递给某些程序时,这尤其有用。
myProgram $'foo\nbar'
你可以看到 hexdump
形成的字符串。不要混淆尾随的新行,因为它是由此处的字符串 <<<
引入的 build 于 bash
$ hexdump -c <<< $'foo\nbar'
0000000 f o o \n b a r \n
0000008
还支持以下转义序列,在此处更新列表,因为它在重复的序列中不可用。
+-------------+----------------------------------------------------------------------------------------------------------------------------------+
| code | meaning |
| | |
+-------------+----------------------------------------------------------------------------------------------------------------------------------+
| \" | double-quote |
| \' | single-quote |
| \\ | backslash |
| \a | terminal alert character (bell) |
| \b | backspace |
| \e | escape (ASCII 033) |
| \E | escape (ASCII 033) \E is non-standard |
| \f | form feed |
| \n | newline |
| \r | carriage return |
| \t | horizontal tab |
| \v | vertical tab |
| \cx | a control-x character, for example, $'\cZ' to print the control sequence composed of Ctrl-Z (^Z) |
| \uXXXX | Interprets XXXX as a hexadecimal number and prints the corresponding character from the character set (4 digits) (Bash 4.2-alpha)|
| \UXXXXXXXX | Interprets XXXX as a hexadecimal number and prints the corresponding character from the character set (8 digits) (Bash 4.2-alpha)|
| \nnn | the eight-bit character whose value is the octal value nnn (one to three digits) |
| \xHH | the eight-bit character whose value is the hexadecimal value HH (one or two hex digits) |
+-------------+----------------------------------------------------------------------------------------------------------------------------------+
关于bash - 在 bash 中传递换行符(LF)/换行符作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46885958/