在 bash 中嵌套引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6611648/
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
Nesting quotes in bash
提问by Tyilo
I want to something like this in bash:
我想在 bash 中做这样的事情:
alias foo='bar="$(echo hello world | grep \"hello world\")"; echo $bar;'; foo
Expected output: hello world
预期输出:你好世界
Ouput: grep: world": No such file or directory
输出:grep:world”:没有那个文件或目录
The outer quotes have to be single quotes, with double quotes $bar would be empty.
The next quotes have to be double quotes, with single quotes $() wouldn't expand.
The inner quotes could be both type of quotes, but single quotes doesn't allow single quotes inside of them.
外部引号必须是单引号,双引号 $bar 将为空。
下一个引号必须是双引号,单引号 $() 不会扩展。
内引号可以是两种类型的引号,但单引号不允许在其中包含单引号。
How to I achieve this?
我如何实现这一目标?
回答by glenn Hymanman
The stuff inside $()represents a subshell, so you are allowed to place un-escaped double quotes inside
里面的东西$()代表一个子shell,所以你可以在里面放置未转义的双引号
alias foo='bar="$(echo testing hello world | grep "hello world")"; echo "$bar"'
回答by l0b0
It's a bit unclear what "something like this" means, but the simplest way to achieve what seems to be the point here is a simple function:
有点不清楚“像这样的东西”是什么意思,但实现这里似乎是重点的最简单方法是一个简单的函数:
foo() {
echo 'hello world' | grep 'hello world'
}
foo
- There's no need for an intermediate variable assignment (it will be lost anyway).
- Functions are generally preferred over aliases because of more flexibility (parameter handling) and readability (multiple lines; less escaping).
- Always use the simplest solution which could possibly work.
- 不需要中间变量赋值(无论如何它都会丢失)。
- 函数通常比别名更受欢迎,因为它具有更大的灵活性(参数处理)和可读性(多行;更少的转义)。
- 始终使用可能有效的最简单的解决方案。
回答by Karoly Horvath
Escape the spaces
逃离空间
alias foo='bar="$(echo hello world | grep hello\ world)"; echo $bar;'
回答by bmk
The double quotes around $()are not necessary:
周围的双引号$()不是必需的:
alias foo='bar=$(echo hello world | grep "hello world"); echo $bar;'
foo
# Output:
hello world

