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

获取bash函数的前n个参数以外的所有参数

  •  3
  • ted  · 技术社区  · 7 年前

    我知道如何 get the last argument passed to a function 但我想知道,在前两个函数之后,如何获取函数的所有参数:

    例如:

    function custom_scp(){
        PORT=$1
        USER=$2
        SOURCES=`ALL_OTHER_ARGS`
        scp -P $PORT -r $SOURCES $USER@myserver.com:~/
    }
    

    所以把三个文件发送到遥控器 home 目录应该是

    $ custom_scp 8001 me ./env.py ./test.py ./haha.py
    
    2 回复  |  直到 7 年前
        1
  •  5
  •   John Kugelman Michael Hodel    7 年前

    可以使用数组切片表示法:

    custom_scp() {
        local port=$1
        local user=$2
        local sources=("${@:3}")
    
        scp -P "$port" -r "${sources[@]}" "$user@myserver.com:~/"
    }
    

    引用 Bash manual :

    ${parameter:offset}
    ${parameter:offset:length}

    如果 参数 @ 结果是 长度 位置参数开始于 抵消 .

        2
  •  5
  •   Charles Duffy    7 年前

    只是 shift 从前面的,你已经处理好了,剩下的就在里面了。 "$@" .

    这具有与所有POSIX shell兼容的优点(下面使用的唯一扩展是 local 这是一个广泛的,甚至在 dash )

    custom_scp() {
      local user port  # avoid polluting namespace outside your function
      port=$1; shift   # assign to a local variable, then pop off the argument list
      user=$1; shift   # repeat
      scp -P "$port" -r "$@" "${user}@myserver.com:~/"
    }
    
    推荐文章