How to store a command in a variable in a shell script?

前端 未结 8 1086
长情又很酷
长情又很酷 2020-11-22 07:35

I would like to store a command to use at a later period in a variable (not the output of the command, but the command itself)

I have a simple script as follows:

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 08:04

    var=$(echo "asdf")
    echo $var
    # => asdf
    

    Using this method, the command is immediately evaluated and it's return value is stored.

    stored_date=$(date)
    echo $stored_date
    # => Thu Jan 15 10:57:16 EST 2015
    # (wait a few seconds)
    echo $stored_date
    # => Thu Jan 15 10:57:16 EST 2015
    

    Same with backtick

    stored_date=`date`
    echo $stored_date
    # => Thu Jan 15 11:02:19 EST 2015
    # (wait a few seconds)
    echo $stored_date
    # => Thu Jan 15 11:02:19 EST 2015
    

    Using eval in the $(...) will not make it evaluated later

    stored_date=$(eval "date")
    echo $stored_date
    # => Thu Jan 15 11:05:30 EST 2015
    # (wait a few seconds)
    echo $stored_date
    # => Thu Jan 15 11:05:30 EST 2015
    

    Using eval, it is evaluated when eval is used

    stored_date="date" # < storing the command itself
    echo $(eval "$stored_date")
    # => Thu Jan 15 11:07:05 EST 2015
    # (wait a few seconds)
    echo $(eval "$stored_date")
    # => Thu Jan 15 11:07:16 EST 2015
    #                     ^^ Time changed
    

    In the above example, if you need to run a command with arguments, put them in the string you are storing

    stored_date="date -u"
    # ...
    

    For bash scripts this is rarely relevant, but one last note. Be careful with eval. Eval only strings you control, never strings coming from an untrusted user or built from untrusted user input.

    • Thanks to @CharlesDuffy for reminding me to quote the command!

提交回复
热议问题