0

May you please explain what does this mean:

@:1:$#-1

can you provide an exact explanation?

admin
  • 3
  • 2
  • Can you also explain what it does? – Aplet123 Jan 16 '20 at 14:20
  • In the linked duplicate *Using ${1:1} in bash*, see [the answer by Etan Reisner](https://stackoverflow.com/a/30197363/14122), which quotes the manual including specifically the parts relevant to `$@`; whereas "Slicing an array in bash" is *precisely* on-point, just coming from the "how do I do this?" perspective instead of the "what does this do?" one. – Charles Duffy Jan 16 '20 at 14:30
  • ...whereas the *Bash: all of array except last element* duplicate explicitly describes the `$#-1` part. – Charles Duffy Jan 16 '20 at 14:33
  • 1
    That said, this code is buggy in its entirety -- a list of arguments (like you get when you slice `$@`) is not a string, and you lose information when you assign it *to* a string. Consider `set -- "first element" "second element" "third element" "fourth element"`; running `temp=${@:1:$#-1}` would set `temp="second element third element"`, with no way to know where `second element` stops and `third element` starts. – Charles Duffy Jan 16 '20 at 14:34

1 Answers1

3

That's a parameter expansion that returns all the positional parameters but the last one.

It's based on ${parameter:offset:length}, where using @ as parameter makes it work on positional parameters. The length $#-1 is the number of positional parameters ($#) minus one.

Here's a showcase : https://ideone.com/HKcaNj

Toby Speight
  • 23,550
  • 47
  • 57
  • 84
Aaron
  • 21,986
  • 2
  • 27
  • 48
  • I was going to mention it would only work appropriately in a function or script, but your showcase example illustrates this quite nicely. – h0r53 Jan 16 '20 at 14:26
  • @h0r53 actually you could make it work in a shell by using `set` which lets you modify positionnal parameters. That would admitedly be stupid, but you could ! – Aaron Jan 16 '20 at 14:29
  • 2
    It's worth noting that the OP is here assigning the result to a string, thus flattening it `$*`-style; typically, that's not behavior that should be encouraged -- as a typical usage is to later call `someprogram $temp`, hitting the bugs [BashFAQ #50](http://mywiki.wooledge.org/BashFAQ/050) teaches how to avoid. – Charles Duffy Jan 16 '20 at 14:39