Kevin
Kevin

Reputation: 1569

How to exclude bash input arguments in "$*"

Basically, I want to be able to call $* in a bash script, to represent all arguments after the script is called, but I want it to ignore the first two. ($1 and $2)

So for simplicity's sake, if all the script did was just echo back the arguments, it should behave as such:

$ myscript.sh first_argument second_argument foo bar baz blah blah etc
foo bar baz blah blah etc

Is there an easy way to do this? By the way, there should be no limit to the amount of text after the first and second argument, if that amount were known, I could easily call them individually, like $3 $4 $5 $6 ...

I hope that was clear.

Thanks,

Kevin

Upvotes: 2

Views: 2906

Answers (4)

Kerrek SB
Kerrek SB

Reputation: 476990

Use shift:

#!/bin/sh

shift 2

echo $@

./myscript A B C D outputs C D.

This will fail if there are fewer than 2 arguments, use $# to check.

Here is a fairly comprehensive documentation of shift.

Upvotes: 5

Gordon Davisson
Gordon Davisson

Reputation: 125748

You can use a variant of array slicing to pick out a range of arguments. To print the arguments from 3 on, use this:

echo "${@:3}"

Unlike the shift-based option, this doesn't mess up the argument list for other purposes.

Upvotes: 7

Andrew Young
Andrew Young

Reputation: 331

Here you go, this puts all the args except the first two in an array, which you can then loop over or whatever.

#!/bin/bash

declare -a args

count=1
index=1
for arg in "$@"
do
    if [ $count -gt 2 ]
    then
        args[$index]=$arg
        let index=index+1
    fi
    let count=count+1
done

for arg in "${args[@]}"
do
    echo $arg
done

Upvotes: 0

Ivan Danilov
Ivan Danilov

Reputation: 14777

Probably shift will help you.

Upvotes: 0

Related Questions