Feng Tian
Feng Tian

Reputation: 1589

How to obtain the variable except the options in bash scripts?

I made a script and the usage should be:

bash test.sh -r chr1:1000-2000 -n 123 test_1.fq test_2.fq

I want to get the input test_1.fq test_2.fq at the end of input.

But when I used $* in the script, input=$*, I just got the whole input -r chr1:1000-2000 -n 123 test_1.fq test_2.fq.

Other options (-r -n) were obtained normally using getopts.

How could I keep only the last two words?

Upvotes: 0

Views: 217

Answers (2)

JCx
JCx

Reputation: 2769

Use shift:

http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_09_07.html

It removes the left most parameters. If you know the number you need to remove then this is the solution. If you know how many you need after shifting then the other answer will work :)

$ ./a.sh 1 2 3 4 5 6 7
+ shift 4
+ echo 5 6 7
5 6 7

Upvotes: 1

fedorqui
fedorqui

Reputation: 290525

Just shift all the parameters until you just have two:

while (( $# > 2 )); do
   shift
done

echo "$@"

From the linked page:

The shift builtin command is used to "shift" the positional parameters by the given number n or by 1, if no number is given.

Note also that the way to use the given parameters is with $@, not $*.

Upvotes: 1

Related Questions