Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell scripting: get a specified range of parameters

Tags:

shell

I normally come here if google doesnt work. So this time it goes like this: In a function, i want to assign to a variable from the 4-th input parameter onward. Example:

function foo {  
  var="$4$5$6..."   
  use var  
  commands using $1, etc  
}

So i think i cannot use shift, since i want to use $1 afterwards. I do not either want to use an extra var to store $1,$2,$3 and shift. So how should it work?

like image 979
lukmac Avatar asked Dec 29 '22 06:12

lukmac


2 Answers

function foo {
    var=${@:4}
    # ...
}
like image 88
Alex Howansky Avatar answered Jan 09 '23 08:01

Alex Howansky


Someone wanted a version without bashisms? Okay, but you won't like it.

#!/bin/sh

do_something () {
        i=4
        var=
        while [ $i -lt 10 ] ; do
                tmp=
                eval tmp=\"'$'$i\"
                if [ -z "$tmp" ] ; then
                        break
                else
                        var="$var$tmp"
                fi
                i=$(($i+1))
        done
        echo $var
}

do_something one two three four five six "six and a half" seven eight nine

I tested this with dash and FreeBSD's sh, but I cannot really guarantee the portability of evaling things. I also had to limit it to parameters $1 to $9, since after that it stops working.

like image 26
sorpigal Avatar answered Jan 09 '23 10:01

sorpigal