0

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
  • 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 9 '18 at 13:20
  • 2
    @JeffSchaller, even worse if you have a file called 1 in the current directory – ilkkachu May 9 '18 at 13:25
  • Thanks for the edit, @ilkkachu, and good point! (Or even a file named ,!) – Jeff Schaller May 9 '18 at 13:35
  • Related to the above discussion: unix.stackexchange.com/q/347950/117549 – Jeff Schaller May 9 '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 9 '18 at 13:44
7

That is a (nonstandard) 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
  • 2
    Happy to hear, Siddhartha! Welcome to the site. Don't forget to take our 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 9 '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.

  • I'm new to this can you please explain in detail – Siddhartha Dasari May 9 '18 at 13:17
  • the 2 is misleading; it's worth pointing out that it's not the second character in human terms, but in computer "count from zero" terms. – Jeff Schaller May 9 '18 at 13:25
  • @JeffSchaller thanks for pointing that out. Fixed – Federico klez Culloca May 9 '18 at 13:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.