Does variable=$(…) store the command or the result of the command in POSIX sh

前端 未结 3 924
南方客
南方客 2020-12-12 07:54

I was wondering: When I e.g. call

list=$(ps -ax)

is ps -ax executed once and I can read the value multiple times or is the command executed e

3条回答
  •  心在旅途
    2020-12-12 08:31

    To cite the bash manpage:

    Command Substitution
        Command substitution allows the output of a com-
        mand to replace the command name. There are two forms:
            $(command)
        or
            `command`
    

    So the output of the command is stored, not the command itself. If you want to store a command that is evaluated each time, you need to use eval:

    #!/bin/bash
    
    command="date"
    startTime=$(date)
    for i in `seq 1 4`
    do
        echo "$i: $startTime - " $(eval $command)
        sleep 1
    done
    

提交回复
热议问题