HindK
HindK

Reputation: 142

Bash: Running one command after another using string variable

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.

Upvotes: 0

Views: 538

Answers (1)

HuntM
HuntM

Reputation: 157

When you put two command in a single string variable, it is executed as single command. so when you are using "$TestCommand" to execute two "ls" commands, it is executing only one(first) "ls" command. it considers && and ls(second) as argument of first ls command.

As your current working directory is not having any files named && and ls it is returning error :

    ls: cannot access &&: No such file or directory
    ls: cannot access ls: No such file or directory

So, basically your commands behaves like this

    ls file1 file2 -l

and it will give you output like this if file1 and file2 exists:

    HuntM@~/scripts$ ls file1 file2 -l
    -rw-r--r-- 1 girishp staff 0 Dec  8 12:44 file1
    -rw-r--r-- 1 girishp staff 0 Dec  8 12:44 file2

Now your solution:

You can create function OR one more script to execute 2 commands as below:

caller.sh

    #!/bin/bash
    myLs=`./myls.sh`
    echo "$myLs"

myls.sh

    #!/bin/bash
    ls && ls -l

Upvotes: 1

Related Questions