Question

How to I remove the nth element from an argument list in bash?

Shift only appears to remove the first n, but I want to keep some of the first. I want something like:

#!/bin/sh
set -x

echo $@

shift (from position 2)

echo $@

So when I call it - it removes "house" from the list:

my.sh 1 house 3
1 house 3
1 3
Was it helpful?

Solution

Use the set builtin and shell parameter expansion:

set -- "${@:1:1}" "${@:3}"

would remove the second positonal argument.

You could make it generic by using a variable:

n=2   # This variable denotes the nth argument to be removed
set -- "${@:1:n-1}" "${@:n+1}"

OTHER TIPS

a=$1
shift; shift

echo $a $@

If someone knows how to do this in a better way I am all ears!

If you want to use bash you can use a bash array

#!/bin/bash

arg=($0 $@)

or if you don't need argument $0

arg=($@)

# argument to remove
rm_arg=2
arg=(${arg[@]:0:$rm_arg} ${arg[@]:$(($rm_arg + 1))})

echo ${arg[@]}

Now instead of referencing $1 you might use ${arg[1]} .

Remember that bash arguments has an argument $0 and bash arrays have an element [0]. So, if you don't assign bash argument $0 to the first element of a bash array [0] , Then you will find bash argument $1 in your bash array [0] .

arg=($@)
for VAR in $@; do
    case $VAR in
    A)
        echo removing $VAR
        arg=($(echo $@| sed "s/$VAR//"))
        ;;
      *)
        echo ${arg[@]}
        ;;
    esac
done

Results:

./test.sh  1 2 3 A 4 5
1 2 3 A 4 5
1 2 3 A 4 5
1 2 3 A 4 5
removing A
1 2 3 4 5
1 2 3 4 5
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top