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.
-
"Bourne shell" (as per the title) or "Bourne Again Shell (bash)" (as per the tags)?– johnsywebCommented Oct 5, 2011 at 3:59
-
1How do you print the last argument if 0 arguments are passed?– Adam RosenfieldCommented Oct 5, 2011 at 4:06
-
it should simply return nothing.– BeagleBoy360Commented Oct 5, 2011 at 4:26
5 Answers
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 withecho "${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" ]
)
lastArg=`echo $@ | awk '{print $NF}'`
-
#!/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?– jdiCommented Oct 5, 2011 at 17:41
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
-
I should note that at one point this question was tagged "bash". Commented Feb 8, 2013 at 4:31
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];
[...]
}
-
#!/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
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.