2

I'm wondering how to obtain the last argument passed to a bash function, like this:

#!/bin/bash

function hello() {
    all=$@         # all arguments
    n=$#           # number of arguments
    first_arg=$1   # argument one
    last_arg= ???  # How to get the last argument?
}

How to set $last_arg to the value of the last argument passed to the function?

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
Alan
  • 1,479
  • 3
  • 20
  • 36
  • @GregHilston Does that excludes the last argument from the second variable? – Alan Jun 11 '15 at 12:25
  • Downvote beacuse you posted your whole shell script here. Why are the `sed` commands and other stuff interesting for us? Your example should look like this: http://pastebin.com/vyp0drSs Do you was too lazy to make a simple example out of it? I don't understand why somebody should post something like this. – hek2mgl Jun 11 '15 at 12:26
  • Hi @hek2mgl, I posted the whole script so you can test its functionality, if needed. I'm trying to follow the rules: http://stackoverflow.com/help/mcve – Alan Jun 11 '15 at 12:28
  • @hek2mgl I didn't know that tool, thank you. – Alan Jun 11 '15 at 12:29
  • `…Complete` means `Provide all parts needed to reproduce the problem` and means not post your whole shell script. – hek2mgl Jun 11 '15 at 12:29
  • Good to hear that you are at least aware of the the `How to ask` page. You need to get a better feeling of what is important and what not. – hek2mgl Jun 11 '15 at 12:31
  • 1
    I've edited it. Doesn't it look much more clean now? – hek2mgl Jun 11 '15 at 12:34
  • It does, indeed. I was going to edit like this add_a(){ var1=$1 var2=$@ - first and last var3=last } but it looks better that way, thank you – Alan Jun 11 '15 at 12:36
  • Moderators: if the question has been asked before and already has an answer, please include the link to the answer in your rejection. – Peter Flynn Jul 11 '18 at 14:58

1 Answers1

2

If all holds the $@, then the last argument is ${all[*]: -1}

Eugeniu Rosca
  • 5,177
  • 16
  • 45