Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nesting quotes in bash

Tags:

bash

escaping

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 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.

How to I achieve this?

like image 709
Tyilo Avatar asked Jul 07 '11 13:07

Tyilo


People also ask

How do you quote within a quote in bash?

Single quotes(') and backslash(\) are used to escape double quotes in bash shell script. We all know that inside single quotes, all special characters are ignored by the shell, so you can use double quotes inside it. You can also use a backslash to escape double quotes.

How do you nest a quote?

Use single quotes for a nested quotation, when someone repeats what someone else said. Joe smiled and said, "Jenny said 'yes' when I asked her to marry me." If you need another layer of quotation, just keep alternating between single and double quotation marks.

What is double quotes in bash?

3.1.2.3 Double Quotes Enclosing characters in double quotes (' " ') preserves the literal value of all characters within the quotes, with the exception of ' $ ', ' ` ', ' \ ', and, when history expansion is enabled, ' ! '. When the shell is in POSIX mode (see Bash POSIX Mode), the ' !

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.


1 Answers

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"'
like image 68
glenn jackman Avatar answered Sep 17 '22 15:09

glenn jackman