LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Need help with script writing: Storing cmd in variable, print variable, then exe cmds (https://www.linuxquestions.org/questions/programming-9/need-help-with-script-writing-storing-cmd-in-variable-print-variable-then-exe-cmds-924127/)

Arodef 01-16-2012 08:39 PM

Need help with script writing: Storing cmd in variable, print variable, then exe cmds
 
I have a script which contains sections that store a command to a variable, prints out the command, then executes it.

Example:
Code:

MYCOMMAND="cp file1.txt $NEWFILE"
echo "Running $MYCOMMAND"
$MYCOMMAND


The above works when I save a single command to the string like I did above. However I want to store a string made up of multiple commands separated by && or ;. Example:

Code:

MYCOMMAND="cp file1.txt $NEWFILE && rm file1.txt && echo done"
echo "Running $MYCOMMAND"
$MYCOMMAND

When I separate the commands with && or ;, the whole string is echoed correctly, but only the first command actually gets executed. So the cp in the above example get executed, the rm and 'echo done' are not run.

How I can save a string with multiple commands in it to a single variable, echo that variable so the commands that are going to be run are printed out first, and then actually run the commands stored in that variable?

fsainsbu 01-16-2012 09:31 PM

NEWFILE=emp.2.txt
MYCOMMAND="cp file1.txt $NEWFILE ; rm file1.txt ; echo done"
echo "Running $MYCOMMAND"
echo $MYCOMMAND |sh

Valery Reznic 01-16-2012 11:50 PM

You can use 'set -x'

Either this way if you want to trace every command in your script:
Code:

#!/bin/bash -x

your script

Or this way for only selected commands:
Code:

#!/bin/bash
...
commands
...
set -x
# those commands will be traced
commands
set +x

# those commands will not be traced
commands


catkin 01-17-2012 12:26 AM

Quote:

Originally Posted by fsainsbu (Post 4576426)
NEWFILE=emp.2.txt
MYCOMMAND="cp file1.txt $NEWFILE ; rm file1.txt ; echo done"
echo "Running $MYCOMMAND"
echo $MYCOMMAND |sh

Nice technique :)

But, if any of the command arguments include whitespace (space, tab or newline), it will fail. More information about wanting to execute complex commands held in a bash variable in Greg's Bash FAQ.


All times are GMT -5. The time now is 10:14 AM.