Tyilo
Tyilo

Reputation: 30161

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

How to I achieve this?

Upvotes: 14

Views: 14235

Answers (4)

glenn jackman
glenn jackman

Reputation: 247210

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"'

Upvotes: 34

bmk
bmk

Reputation: 14147

The double quotes around $() are not necessary:

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

# Output:
hello world

Upvotes: 0

l0b0
l0b0

Reputation: 58988

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.

Upvotes: 5

Karoly Horvath
Karoly Horvath

Reputation: 96326

Escape the spaces

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

Upvotes: 1

Related Questions