LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (http://www.linuxquestions.org/questions/linux-general-1/)
-   -   bash: execute a semicolon separated list of commands within string (http://www.linuxquestions.org/questions/linux-general-1/bash-execute-a-semicolon-separated-list-of-commands-within-string-673660/)

Meson 10-01-2008 11:42 PM

bash: execute a semicolon separated list of commands within string
 
Could someone explain this behavior and how to fix it.

Code:

#! /bin/bash

cmd="echo ONE; echo TWO; echo THREE;"
echo RUN
$cmd

produces this:
Code:

RUN
ONE; echo TWO; echo THREE;

I obviously want three echos.

Mr. C. 10-02-2008 12:03 AM

Use eval $cmd

The quotes protected the semicolons.

Meson 10-02-2008 12:04 AM

If you're not married you can have my first born daughter.

Quote:

Originally Posted by Mr. C. (Post 3297618)
The quotes protected the semicolons.

I figured that but I didn't know how to un-protect them. \; didn't work

Mr. C. 10-02-2008 12:25 AM

The shell assigned the entire string. Then, when you ran:

$cmd

The shell expanded the string, and tries to execute the first word, using the remaining words as arguments. Thus, you get:

echo ONE; echo TWO; echo THREE;

This occurs because your command is a simple command expansion:

man bash:
Quote:

SIMPLE COMMAND EXPANSION
When a simple command is executed, the shell performs the following
expansions, assignments, and redirections, from left to right.

1. The words that the parser has marked as variable assignments
(those preceding the command name) and redirections are saved
for later processing.

2. The words that are not variable assignments or redirections are
expanded. If any words remain after expansion, the first word
is taken to be the name of the command and the remaining words
are the arguments
.


All times are GMT -5. The time now is 07:46 PM.