删除Bash中的位置参数?

She*_*ley 11 parameters bash shell

您可以跳过位置参数shift但是可以通过传递位置来删除位置参数吗?

x(){ CODE; echo "$@"; }; x 1 2 3 4 5 6 7 8
> 1 2 4 5 6 7 8
Run Code Online (Sandbox Code Playgroud)

我想添加CODE来x()删除位置参数3.我不想这样做echo "${@:1:2} ${@:4:8}".运行CODE后,$@应该只包含"1 2 4 5 6 7 8".

l0b*_*0b0 8

如果您希望能够将参数传递给另一个进程或处理空格分隔的参数,最好的方法是重新set参数:

$ x(){ echo "Parameter count before: $#"; set -- "${@:1:2}" "${@:4:8}"; echo "$@"; echo "Parameter count after: $#"; }
$ x 1 2 3 4 5 6 7 8
Parameter count before: 8
1 2 4 5 6 7 8
Parameter count after: 7
Run Code Online (Sandbox Code Playgroud)

要测试它是否适用于非平凡的参数:

$ x $'a\n1' $'b\b2' 'c 3' 'd 4' 'e 5' 'f 6' 'g 7' $'h\t8'
Parameter count before: 8
a
1 2 d 4 e 5 f 6 g 7 h   8
Parameter count after: 7
Run Code Online (Sandbox Code Playgroud)

(是的,$'\b'是退格)


小智 6

x(){
    #CODE
    params=( $* )
    unset params[2]
    set -- "${params[@]}"

    echo "$@"
}
Run Code Online (Sandbox Code Playgroud)

输入:x 1 2 3 4 5 6 7 8

输出:1 2 4 5 6 7 8


Fre*_*ihl 5

来自tldp

# The "unset" command deletes elements of an array, or entire array.
unset colors[1]              # Remove 2nd element of array.
                             # Same effect as   colors[1]=
echo  ${colors[@]}           # List array again, missing 2nd element.

unset colors                 # Delete entire array.
                             #  unset colors[*] and
                             #+ unset colors[@] also work.
echo; echo -n "Colors gone."               
echo ${colors[@]}            # List array again, now empty.
Run Code Online (Sandbox Code Playgroud)

  • `x(){local -a parms =("$ @"); 未设置的parms [2]; 设置 - "$ {parms [@]}"; echo"$ @"; }`.但是,在unset命令之后,你不妨使用``$ {parms [@]}"`而不是`"$ @"`. (5认同)