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.
Explanation
The number of arguments is
$#. Variables can be accessed indirectly via${!VAR}. For example:Put those together and if we have a variable
$ncontaining an integer we can access the$nth command-line argument with${!n}. Or instead of$nlet’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:Oddly, you cannot use an array index: