Shell scripting: get the given range of parameters

I usually come here if google does not work. So, this time it happens as follows: In the function, I want to assign a variable from the 4th input parameter forward. Example:

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

So I think I can’t use shift, since I want to use $ 1 after that. I do not want to use extra var to store $ 1, $ 2, $ 3 and shift. So how should this work?

+3
source share
3 answers
function foo {
    var=${@:4}
    # ...
}
+7
source

Someone wanted a version without bugs? Good, 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

FreeBSD sh, . $1 $9, .

+1

In addition to the answer from Alex:

All arguments except the last:

var=${@:1:${#}-1}

Last argument:

var=${@:${#}}  

or POSIX:
eval var=\${{#}}
0
source

Source: https://habr.com/ru/post/1769193/


All Articles