Bash function calling command given as argument

后端 未结 2 1801
伪装坚强ぢ
伪装坚强ぢ 2021-01-02 09:21

How do you write a function in bash that executes the command that it is given as an argument, where

  • The given command may be an alias
  • Arguments must
相关标签:
2条回答
  • 2021-01-02 09:49

    You (uh, I) can use printf %q to escape the arguments. At first sight, escaping with printf and then doing eval always gives the same result as passing the arguments directly.

    wrap() {
        echo Starting: "$@"
        eval $(printf "%q " "$@")
    }
    
    0 讨论(0)
  • 2021-01-02 09:57

    It seems to be possible with a double eval:

    eval "eval x=($(alias y | cut -s -d '=' -f 2))"
    # now the array x contains the split expansion of alias y
    "${x[@]}" "${other_args[@]}"
    

    So maybe your function could be written as follows:

    wrap() {
        eval "eval prefix=($(alias $1 | cut -s -d '=' -f 2))"
        shift
        "${prefix[@]}" "$@"
    }
    

    However, eval is evil, and double eval is double evil, and aliases are not expanded in scripts for a reason.

    0 讨论(0)
提交回复
热议问题