LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Shellscript variable as command string (http://www.linuxquestions.org/questions/linux-newbie-8/shellscript-variable-as-command-string-947939/)

psrdotcom 06-01-2012 04:53 AM

Shellscript variable as command string
 
Hi Friends,

When I was trying form a command from different variables to one variable, I was successive.

Sample:

CMD="mount"

CMD=$CMD" /dev/sdb"

CMD=$CMD" /mnt/disk0/"

echo "The command is: $CMD"

$CMD

Output:
The command is: mount /dev/sdb /mnt/disk0
Error: No such file or directory:
""

Note: Both the /dev/sdb and /mnt/disk0 exists.

If I am running the same command without using variable from the script, it was working fine.

Please help me to get out of this problem.

evo2 06-01-2012 05:26 AM

Hi,

seems to be a quoting issue. Can you try the following
Code:

CMD="mount"
CMD="$CMD /dev/sdb"
CMD="$CMD /mnt/disk0/"
echo "The command is: $CMD"
$CMD

Evo2.

David the H. 06-01-2012 07:41 AM

The simple answer here is that you don't do it that way. Variables are for storing data, not code.

I'm trying to put a command in a variable, but the complex cases always fail!
http://mywiki.wooledge.org/BashFAQ/050


Once a string is stored in a variable, the parsing rules for it are very different, and you just can't reliably run a complex command that way. If you want to set up a dynamic command of some kind, use a function.


Code:


CMD() {

        echo "The command is: mount $@"
        mount "$@"

}

CMD /dev/sdb /mnt/disk0


psrdotcom 06-01-2012 03:34 PM

Solved
 
I have wrote the command to a file and executed the file within the script.


Quote:

Originally Posted by David the H. (Post 4692925)
The simple answer here is that you don't do it that way. Variables are for storing data, not code.

I'm trying to put a command in a variable, but the complex cases always fail!
http://mywiki.wooledge.org/BashFAQ/050


Once a string is stored in a variable, the parsing rules for it are very different, and you just can't reliably run a complex command that way. If you want to set up a dynamic command of some kind, use a function.


Code:


CMD() {

        echo "The command is: mount $@"
        mount "$@"

}

CMD /dev/sdb /mnt/disk0




All times are GMT -5. The time now is 09:20 AM.