Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: execute a multi-command line string in a script

Tags:

linux

bash

unix

There is, in a file, some multi-command line like this:

cd /home/user; ls

In a bash script, I would like to execute these commands, adding some arguments to the last one. For example:

cd /home/user; ls   -l *.png

I thought it would be enough to do something like this:

#!/bin/bash
commandLine="$(cat theFileWithCommandInside)   -l *.png"
$commandLine
exit 0

But it says:

/home/user;: No such file or directory

In other words, the ";" character doesn't mean anymore "end of the command": The shell is trying to find a directory called "user;" in the home folder...

I tried to replace ";" with "&&", but the result is the same.

like image 365
taalf Avatar asked Sep 19 '26 00:09

taalf


2 Answers

the point of your question is to execute command stored in string. there are thousands of ways to execute that indirectly. but eventually, bash has to involve.

so why not explicitly invoke bash to do the job?

bash -c "$commandLine"

from doc:

-c string

If the -c option is present, then commands are read from string. If there are arguments after the string, they are assigned to the positional parameters, starting with $0.

http://linux.die.net/man/1/bash

like image 180
Jason Hu Avatar answered Sep 20 '26 15:09

Jason Hu


Why dont you execute the commands themselves in the script, instead of "importing" them?

#!/bin/bash
cd /home/user; ls -l *.png
exit 0
like image 39
Dragan Avatar answered Sep 20 '26 16:09

Dragan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!