Bash function calling command given as argument

后端 未结 2 1819
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  萌比男神i
    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.

提交回复
热议问题