does someone knows what ${1:1}
means in bash?
For example:
for (( i=0; $i < ${1:1}; i++ ))
do
addToList $2
done
does someone knows what ${1:1}
means in bash?
For example:
for (( i=0; $i < ${1:1}; i++ ))
do
addToList $2
done
That's a bash parameter expansion.
Specifically:
${parameter:offset} ${parameter:offset:length}
This is referred to as Substring Expansion. It expands to up to length characters of the value of parameter starting at the character specified by offset. If parameter is ‘@’, an indexed array subscripted by ‘@’ or ‘*’, or an associative array name, the results differ as described below. If length is omitted, it expands to the substring of the value of parameter starting at the character specified by offset and extending to the end of the value. length and offset are arithmetic expressions (see Shell Arithmetic).
Here are some examples illustrating substring expansion on parameters and subscripted arrays:
$ string=01234567890abcdefgh $ echo ${string:7} 7890abcdefgh
So ${1:1}
is expand the substring of positional parameter 1
starting from the second character (offset
of 1 unspecified length
).
Presumably that is intended to support a script taking arguments something like this:
./addn -10 A
to add ten A
elements to whatever addToList
is adding to.
Though that's a poor way of handling that unless the argument has been checked before that for validity/sanity.
See for yourself:
#!/bin/bash
for (( i=0; $i < ${1:1}; i++ ))
do
echo $i ${1:1}
done
save this into a file named test. Now run this test like this:
./test 45
You will get output:
0 5
1 5
2 5
3 5
4 5
A little explanation what's happening:
you are using arithmetic for loop, so it expects an arithmetic value of ${1:1}
which is actually the second digit of you argument 45
.
$(1:1}
just takes a string from index 1 from the first argument passed in command line and that's 5 for now. if you pass a5
as the argument the output would still be the same. And thus $i
is being looped through 5 times from 0 to 4.
So if you used ${2:1}
, it would expect a second argument i.e you would have to run the test like: ./test 34 455
And this time it would take the value 55
from second argument which is the string from index 1 in this case.