Results 1 to 4 of 4

Thread: [SOLVED] Bash: How to execute command from variable?

  1. #1
    Join Date
    Mar 2007
    Beans
    667

    [SOLVED] Bash: How to execute command from variable?

    Hi,
    on Ubuntu 8.10 I would like to write bash script. From complex transformation I get variable command1 filled. I would like to execute command that is in variable command1.
    Code:
    #!/bin/bash
    command1=$(echo ls -l)   # Variable where some command is defined
    "$command1"              # Execute command
    But the last command returns error:
    line 3: ls -l: command not found

    How to execute command that I already have in variable command1?
    Regards
    Last edited by abcuser; December 22nd, 2008 at 10:44 AM.

  2. #2
    Join Date
    Feb 2008
    Beans
    33

    Re: Bash: How to execute command from variable?

    Use eval.

    Code:
    MYCMD='ls -l'
    eval $MYCMD

  3. #3
    Join Date
    Dec 2008
    Beans
    Hidden!
    Distro
    Ubuntu 14.04 Trusty Tahr

    Re: Bash: How to execute command from variable?

    command1=$(echo ls -l) # Variable where some command is defined
    The above should be:
    Code:
    command='ls -l
    When it is used as:
    Code:
    $command
    It will return
    Code:
    ls -l

  4. #4
    Join Date
    Mar 2007
    Beans
    667

    Re: Bash: How to execute command from variable?

    joehte,
    Just a note. I can have one or multiple commands in command1 variable, so I need to add quotation marks around varialbe.

    Code:
    #!/bin/bash
    command1=$(echo ls -l)   # Variable where some command is defined
    eval "$command1"              # Execute command
    Problems solved. Thanks a lot.
    Regards

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •