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

前端 未结 8 1089
长情又很酷
长情又很酷 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:16

    I tried various different methods:

    printexec() {
      printf -- "\033[1;37m$\033[0m"
      printf -- " %q" "$@"
      printf -- "\n"
      eval -- "$@"
      eval -- "$*"
      "$@"
      "$*"
    }
    

    Output:

    $ printexec echo  -e "foo\n" bar
    $ echo -e foo\\n bar
    foon bar
    foon bar
    foo
     bar
    bash: echo -e foo\n bar: command not found
    

    As you can see, only the third one, "$@" gave the correct result.

提交回复
热议问题