po_taka
po_taka

Reputation: 1846

Bash executing bash command

I have problem running bash command in bash.

Simple:

C="ls"
$C

works

angel@php56:/tmp$ C="ls"
angel@php56:/tmp$ $C
testFile1

Complicated

C="bash -c \"ls\""
$C

works

angel@php56:/tmp$ C="bash -c \"ls\""
angel@php56:/tmp$ $C
testFile1

More complicated

C="bash -c \"bash -c 'ls'\""
$C

doesn't work

angel@php56:/tmp$ C="bash -c \"bash -c 'ls'\""
angel@php56:/tmp$ $C
-c: line 0: unexpected EOF while looking for matching `"'
-c: line 1: syntax error: unexpected end of file

same for C="bash -c \"bash -c \\\"ls\\\"\""

angel@php56:/tmp$ C="bash -c \"bash -c \\\"ls\\\"\""                                                                                                                                                                                               
angel@php56:/tmp$ $C                                                                                                                                                                                                                               
-c: line 0: unexpected EOF while looking for matching `"'                                                                                                                                                                                          
-c: line 1: syntax error: unexpected end of file

Why I can run bash in bash, but cant bash in bash in bash :) May be something with quotes ? Online code: click

Upvotes: 0

Views: 171

Answers (1)

Mark Reed
Mark Reed

Reputation: 95242

The problem is the order of operations with word splitting vs parameter expansion.
It works with eval:

eval "$C"

This gets very tricky very quickly. The best way to deal with dynamic commands that don't include pipes or other redirection is to use arrays:

C=(bash -c "bash -c 'ls'")
"${C[@]}"

Upvotes: 3

Related Questions