2

Can anyone tell me the meaning of ${p:2:1} in shell scripting as in:

var1=""
for p in [1,2,3,4]
do
    var1="${var1} ${p:2:1}"
done
Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
  • 2
    It doesn't seem to be what you're asking about, so I'll just comment here: using `[1,2,3,4]` in the `for` loop means that `p` gets assigned a single value: `[1,2,3,4]` instead of what you *might* have meant: the list `1 2 3 4`, which you would do with `for p in 1 2 3 4 ...` – Jeff Schaller May 09 '18 at 13:20
  • 2
    @JeffSchaller, even worse if you have a file called `1` in the current directory – ilkkachu May 09 '18 at 13:25
  • Thanks for the edit, @ilkkachu, and good point! (Or even a file named `,`!) – Jeff Schaller May 09 '18 at 13:35
  • Related to the above discussion: https://unix.stackexchange.com/q/347950/117549 – Jeff Schaller May 09 '18 at 13:35
  • @JeffSchaller Iterating over the list `1 2 3 4` would make the substitution `${p:2:1}` a bit pointless as it would be empty... But then again, iterating over a single string is also a bit pointless. – Kusalananda May 09 '18 at 13:44
  • Indeed; the actual point of the `for` loop may be a different question, but I wanted to point out the possible misunderstanding as a separate point from the "expansion" question from the title. – Jeff Schaller May 09 '18 at 13:46

2 Answers2

9

That is a parameter expansion (Bash manual), in particular of the form:

${parameter:offset:length}

which is described as "substring expansion". It extracts characters from the variable starting at offset (starting at zero) and going for length characters. In your case, ${p:2:1} extracts the third character.

Example:

$ p=abcd
$ echo "${p:2:1}"
c
Lucas
  • 119
  • 4
Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
  • 2
    Happy to hear, Siddhartha! Welcome to the site. Don't forget to take our [tour](https://unix.stackexchange.com/tour) to earn a badge, then take a moment to absorb the answers to your question and accept the one that you feel is the best solution. That helps the U&L system separate "answered" from "unanswered" questions. Thanks! – Jeff Schaller May 09 '18 at 13:48
0

That's a substring. It's taking from the second character (counting from 0) of the string p a substring of length 1.