Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove nth element from command arguments in bash

Tags:

bash

shift

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
like image 269
ManInMoon Avatar asked Dec 20 '22 15:12

ManInMoon


1 Answers

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}"
like image 70
devnull Avatar answered Jan 07 '23 20:01

devnull