Search code examples
bashshift

How to remove nth element from command arguments in bash


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

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}"