LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   processing command args in bash (https://www.linuxquestions.org/questions/programming-9/processing-command-args-in-bash-367563/)

David the H. 10-10-2017 10:26 PM

Quote:

Originally Posted by tony4260 (Post 5765920)
I'm taking it that these two lines are equivalent:

echo "${@: (-2):2}" # prints the last two arguments.
echo "${ARGV[@]: (-2):2}"

And in those lines the -2 is saying "start 2 back from the last" (the last is -1, the one before that is -2 so:

Yes, pretty much, assuming you copied the argument list into ARGV in the way I posted. Bash treats the "$@" parameter essentially as an array, although there are minor differences based on historical contingency, particularly the 0 index needing to be explicitly expanded. If you just did ARGV=( "$@" ), then the index numbers would fail to match up. That wouldn't affect negative expansion, but it would affect positive expansions. See below.

Quote:

./argumentstuff.bash this that those many
many would be -1, so the -2 is starting at those.

Then the 2 thats after the -2 is saying do that to two items. so if it was ${@: (-2):1} would only delete "those"?
Correct.In the range parameter substitution "${array[@]:idx:num}", the idx is the index of the first entry you want to output, and num is the number of items that you want from that point on. If the first number is negative, it counts backwards from the end of the array. The second number is optional if you want to output the entire range to the end. And as I pointed out above, arrays start from zero by default, except for $@, so ${array[@]:2:3} will expand to elements 3, 4, and 5, and "${@:2:3}" to elements 2, 3, and 4.

Edit: forget that last part. I was rushed for time earlier and got screwed up in my thinking. The two forms output the same, again assuming the array was set with a "$0" index.

orbea 10-18-2017 03:12 AM

A portable solution.
Code:

#!/bin/sh

usage='Some help...'

while [ "$#" -gt 0 ]; do
  option="$1"; shift
  case "$option" in
    -- ) break ;;
    -b|--bar ) printf %s\\n 'bar' ;;
    -f|--foo ) printf %s\\n 'foo' ;;
    -h|--help ) printf %s\\n "$usage" ;;
    * ) printf %s\\n "Unrecognized option '$option', use -h for help."; exit 1 ;;
  esac
done



All times are GMT -5. The time now is 05:21 AM.