开发者

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开发者_C百科 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


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.


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.


Probably shift will help you.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜