删除Bash中的位置参数?

时间:2011-07-06 10:45:41

标签: bash shell parameters

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

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

我想将{CODE}添加到x()以删除位置参数3.我不想echo "${@:1:2} ${@:4:8}"。运行CODE后,$@应仅包含“1 2 4 5 6 7 8”。

5 个答案:

答案 0 :(得分: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

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

$ 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

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

答案 1 :(得分: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.

答案 2 :(得分:5)

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

    echo "$@"
}

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

输出: 1 2 4 5 6 7 8

答案 3 :(得分:0)

您可以随时调用设置和重置位置参数 例如

function q {
echo ${@}
set $2 $3 $4
echo ${@}
set $4
echo ${@}
}

q 1 2 3 4

然后从数组中切出你不想要的东西,下面的代码就是这样......不确定它是否是最好的方法,但是在堆栈上寻找更好的方法; )

#!/bin/bash


q=( one two three four five )

echo -e "
  (remove) { [:range:] } <- [:list:]
                | [:range:] => return list with range removed range is in the form of [:digit:]-[:digit:]
"

function remove {
  if [[ $1 =~ ([[:digit:]])(-([[:digit:]]))?   ]]; then
    from=${BASH_REMATCH[1]}
    to=${BASH_REMATCH[3]}
  else
    echo bad range
  fi;shift
  array=( ${@} )
  local start=${array[@]::${from}}
  local rest
  [ -n "$to" ] && rest=${array[@]:((${to}+1))}  || rest=${array[@]:((${from}+1))}
  echo ${start[@]} ${rest[@]}
}

q=( `remove 1 ${q[*]}` )
echo ${q[@]}

答案 4 :(得分:0)

while使用shift + set循环“$ @”:将每个参数从第一个位置移动到最后一个位置,“test”除外

# remove option "test" from positional parameters
i=1
while [ $i -le $# ]
  do
    var="$1"
    case "$var" in
      test)
        echo "param \"$var\" deleted"
        i=$(($i-1))
      ;;
      *)
        set -- "$@" "$var"
      ;;
    esac
    shift
    i=$(($i+1))
done