I understand that running one command after another is done in bash using the following command
command1 && command2
or
command1; command2
or even
command1 & command2
I also understand that a command stored in a bash variable can be run by simply firing the variable as:
TestCommand="ls"
$TestCommand
Doing the above will list all the files in the directory and I have tested that it does.
But doing the same with multiple commands generates an error. Sample below:
TestCommand="ls && ls -l"
$TestCommand
ls: cannot access &&: No such file or directory
ls: cannot access ls: No such file or directory
My question is why is this happening and is there any workaround?
And before you bash me for doing something so stupid. The preceding is just to present the problem. I have a list of files in my directory and I am using sed to convert the list into a single executable string. Storing that string in a bash variable, I am trying to run it but failing.
evalthat string. You want to execute all the files in a directory? Do you want to abort if one fails? You could go for afor loop.myfunction() { include your commands here }. You can then callmyfunctionany time after it is declared in your code. Also recognize thatcommand1 && command2orcommand1 || command2are called compound commands. Including a';'following a command is simply andend-of-line. I don't believe your bitwise&of commands is doing what you think it is.';'is same as that of'&&'and so is'&'. I couldn't spot the difference. Would you know the difference?';'is not the same as&&. The';'is just anend-of-lineit has no bearing on whether there was a successful completion of the command before it.&&is a compound command operator that effectively says executecommand2if, and only if there is a successful completion ofcommand1incommand1 && command2. Try itls foo; printf "after foo\n"and thenls foo && printf "after foo\n"Now tryls /home || printf "after foo\n"(||meaning ifcommand1fails, thencommand2.command1 & command2is nothing but a bitwise and of the returns of 1 & 2. Hope this helped.'&'separator or terminator shall cause asynchronous execution of the preceding list of compound commands. (e.g. it causes the preceding command to be executed in the background, rather than synchronously with the command that follows. Note. compound command is also known as an asynchronous list or and-or list in POSIX shell. (see e.g. Asynchronous Lists ) I wasn't thinking about it as a connector, but it is, just strange to think of it that way -- after 20 years