Bash get nth argument

 

Bash arguments are stored in a array.

Getting nth argument is same as getting nth element from an array.

To get nth argument or nth element from an array use following code in your bash script:

n=4
echo ${!n}

where n=4 is to get 4th argument.

I have added above code in bash script and named it as temp.sh

Following is code in my script temp.sh

#!/bin/bash
n=4
echo ${!n}

By using following command execute temp.sh script:

$ bash temp.sh a b c d e

Output:

d

Since 4th argument for our script is d we got output as d.

Another way to get nth argument or nth element from an array is by suing array slicing.

Instead of using echo ${!n} use echo ${@:$n:1} in temp.sh script.

With array slicing my script temp.sh looks like following:

#!/bin/bash
n=4
echo ${@:$n:1}

Again execute script temp.sh:

$ bash temp.sh a b c d e

Output:

d

** Both ways explained in this article only works with bash **

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s