0

Im trying to create a bourne shell script that will take 0 or more arugments and print out the last arugment, I am use to writing Java and im so confused by this, slowly starting to learn C.

3
  • "Bourne shell" (as per the title) or "Bourne Again Shell (bash)" (as per the tags)?
    – johnsyweb
    Commented Oct 5, 2011 at 3:59
  • 1
    How do you print the last argument if 0 arguments are passed? Commented Oct 5, 2011 at 4:06
  • it should simply return nothing. Commented Oct 5, 2011 at 4:26

5 Answers 5

3

An alternative to @Michael's solution:

#!/usr/bin/env bash
echo "${@: -1}"
  • $@ is the array with all the parameters.
  • : is used to split strings normally (you can try this with echo "${USER: -1}" to verify that it prints the last character of your user name), but can also be used for arrays to get the last element.
  • The curly brackets are needed for the array indexing to work
  • The quotes are simply good practice, to make the code more flexible in case you want to mix in other variables, or the value needs to be used in a statement which needs an empty string rather than nothing in case of no parameters (for example if [ "${@: -1}" = "--help" ])
2
lastArg=`echo $@ | awk '{print $NF}'`
2
  • #!/bin/sh read args echo "Enter args: $args" set $args lastArg=echo $@ | awk '{print $NF}' echo $lastArg' Commented Oct 5, 2011 at 3:44
  • @BeagleBoy360 - Is this comment saying that you get it? Or are you correcting something?
    – jdi
    Commented Oct 5, 2011 at 17:41
2

Here is a short Bash script that will do it:

#!/usr/bin/env bash

echo "${!#}"

This is not a Bourne shell script, though. Args are not read from the keyboard with the read command. Instead they are supplied on the command line when running your script. For example, if you put this text in script.sh and run ./script.sh a b c d e it will print:

e
1
  • I should note that at one point this question was tagged "bash". Commented Feb 8, 2013 at 4:31
0

In bash:

last_arg=`echo $* | rev | cut -d " " -f1 | rev`;
echo $last_arg

Your question mentions C. In C its easier:

int main (int argc, char *argv[]) {
     char *last_arg = argv[argc - 1];
     [...]
}
1
  • #!/bin/sh read args echo "Enter args: $args" last_arg=echo $* | rev | cut -d " " -f1 | rev; echo $last_arg Commented Oct 5, 2011 at 3:58
0

This should work:

eval lastarg='$'$#
echo last arg is $lastarg

This works with /bin/sh being bash or dash.

I am unable to test it with a "real" /bin/sh, whatever that would be.

Not the answer you're looking for? Browse other questions tagged or ask your own question.