Delete positional parameters in Bash?

后端 未结 5 2008
野性不改
野性不改 2020-12-15 08:05

You can skip positional parameters with shift but can you delete positional parameters by passing the position?

x(){ CODE; echo \"$@\"; }; x 1 2         


        
5条回答
  •  旧巷少年郎
    2020-12-15 08:52

    You can call set and reset the positional paramaters at any time for example

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

    then slice out what you dont want from the array, the below code does that... not sure if its the best way to do it though, was on stack looking for a better way ; )

    #!/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[@]}
    

提交回复
热议问题