bash -c in subshell gives EOF parsing error

user1658887

Why does the following script work as expected (prints hello)

#!/bin/bash

foo=$(bash -c 'echo hello')
echo $foo

while this script:

#!/bin/bash

cmd="bash -c 'echo hello'"
foo=$($cmd)
echo $foo

gives the following error:

hello': -c: line 0: unexpected EOF while looking for matching `''
hello': -c: line 1: syntax error: unexpected end of file
Stéphane Chazelas

In,

cmd="bash -c 'echo hello'"
$cmd

You're not running the bash -c 'echo hello' command, you're running the $cmd simple command.

That unquoted $cmd means invoking the split+glob operator. Here, with the default value of $IFS, the content of $cmd is split into bash, -c, 'echo and hello'. So, you're running bash with those 4 arguments, it's as if you had typed:

bash -c "'echo" "hello'"

And that 'echo code has a missing closing quote (the hello' argument goes into the $0 of that inline script).

If you want to evaluate the content of $cmd as shell code, it's

eval "$cmd"

So:

cmd="bash -c 'echo hello'"
foo=$(eval "$cmd")
echo "$foo"

Though you could also use your split+glob operator differently:

cmd='bash,-c,echo hello'
IFS=, # split on comma
set -f # disable glob
foo=$($cmd)
echo "$foo"

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Optimizing Bash script, subshell removal

From Dev

Bash subshell mystery

From Dev

Parsing bash command input in C

From Dev

Parenthesis in bash - subshell vs grouping

From Dev

Bash subshell errexit semantics

From Dev

Exit subshell on error

From Dev

Subshell created using (...) behaves differently from bash -c '...'

From Dev

Bash subshell for setting SHELLOPTS in a script

From Dev

Antlr4 recover from error and continue parsing until EOF

From Dev

SageMathCloud: Error: unexpected EOF while parsing

From Dev

Here document gives EOF error in Ruby IO

From Dev

Bash Subshell Variable Command not Found

From Dev

Bash subshell creation with curly braces

From Dev

Bash subshell creation with curly braces

From Dev

Bash script to display directory listing gives error

From Dev

Rule for invoking subshell in Bash?

From Dev

command line argument in bash gives an error

From Dev

Parsing a localstorage object gives uncaught syntax error?

From Dev

Using nice on bash (or other) subshell?

From Dev

bash if not multiple conditions without subshell?

From Dev

Bash: escaped quotes in subshell

From Dev

Put block of bash code in a subshell

From Dev

Here document gives EOF error in Ruby IO

From Dev

On Hadoop installation, bash: gives an 'is a directory error'

From Dev

Bash Subshell Variable Command not Found

From Dev

Bash forking a subshell

From Dev

subshell not propagating error, bash 4.4

From Dev

Syntax Error: Unexpected EOF While Parsing (Small Code)

From Dev

C: Parsing a file with fgetc() - EOF infinite loop