user1696230
user1696230

Reputation:

Bourne shell scripts with user input

I'm trying to teach myself the basics of Bourne shell scripting using a textbook I borrowed from the library, and I'm working through the questions at the end of each chapter. However, I just got to one and I'm stumped...

Write a script that takes zero or more arguments and prints the last argument in the list. For example, given the argument 'myProgram arg1 arg2 arg3', the output would be 'arg3'.

Could anyone give me some advice on how to set this one up? I'm trying to review the section on user input and arguments, but I haven't worked with that much so far, so I don't have much practice yet.

Upvotes: 1

Views: 440

Answers (2)

John Kugelman
John Kugelman

Reputation: 361917

echo ${!#}         # bash only
eval echo \${$#}   # sh-compatible

Explanation

The number of arguments is $#. Variables can be accessed indirectly via ${!VAR}. For example:

$ VAR="PATH"
$ echo ${!VAR}
/sbin:/bin:/usr/sbin:/usr/bin

Put those together and if we have a variable $n containing an integer we can access the $nth command-line argument with ${!n}. Or instead of $n let's use $#; the last command-line argument is ${!#}!


Additionally, this can be more longwindedly written using array slicing ($@ is an array holding all the command-line arguments) as:

echo ${@:$#:$#}

Oddly, you cannot use an array index:

# Does not work
echo ${@[$#]}

Upvotes: 2

Tom W
Tom W

Reputation: 1334

I'll just give you some pointers. Since you want to learn bash, you probably don't just want a piece of code that does what the question asks:

1) Do you know how to count how many arguments your bash function has?

2) Do you know how to loop?

3) Do you know how to "pop" one of the arguments?

4) Do you know how to print out the first argument?

If you put all that together, I bet you'll come up with it.

Upvotes: 0

Related Questions