代码之家  ›  专栏  ›  技术社区  ›  Dhirendra

如何以`$@`作为单个参数执行链式命令?

  •  2
  • Dhirendra  · 技术社区  · 8 年前

    我有一个bash文件 $@

    $@
    

    它通过一个参数接收链接命令。

    ./script.sh "ls && clear"
    


    我想像平常一样执行所有链接的命令。

    2 回复  |  直到 8 年前
        1
  •  1
  •   Miguel RalphMicester    8 年前

    #!/usr/bin/env bash
    
    bash -c "$@"
    
        2
  •  3
  •   Charles Duffy    8 年前

    维护“$@”接口

    如果需要shell语法(复合命令、重定向等),则需要调用shell。因此:

    ./script.sh bash -c 'ls && clear'
    

    …你也需要改变 $@ 到 "$@" 和…的意思完全一样,有-- $* ).


    dir=/tmp # but unlike eval, this is still safe with *any* directory name
    ./script.sh bash -c 'ls "$1" && clear' _ "$dir"
    

    与其他一些方法不同,这仍然让 ./script.sh printf '%s\n' "first line" "second line" 工作。


    使用 "$@" 向用户承诺将处理多个参数;然而, eval "$*" bash -c "$*" bash -c "$@"

    要仅接受一个参数并将其作为代码进行分析,请使用:

    eval "$1"
    

    只接受第一个参数作为代码,保留后续参数作为代码 $1 $2 在该代码的上下文中,使用:

    code=$1; shift; eval "$code"
    
    推荐文章