开发者

Nesting quotes in bash

I want to something like this in 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

  • The outer quotes have to be single quotes, with double qu开发者_如何学Gootes $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.

How to I achieve this?


The stuff inside $() represents a subshell, so you are allowed to place un-escaped double quotes inside

alias foo='bar="$(echo testing hello world | grep "hello world")"; echo "$bar"'


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.


Escape the spaces

alias foo='bar="$(echo hello world | grep hello\ world)"; echo $bar;'


The double quotes around $() are not necessary:

alias foo='bar=$(echo hello world | grep "hello world"); echo $bar;'
foo

# Output:
hello world
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜