17

What is the meaning of the following line in a variable in bash?

VAR=${TEMP:3}
6
  • 1
    @chaos Please do not edit the question to match your answer better ;-).
    – Pilot6
    Oct 6, 2015 at 14:28
  • @Pilot6 I haven't changed the meaning. Or do I understand something wrong? I made it better to find (title) and more readable.. BTW : has also other meanings, it's a bash builtin command, for example. I wanted to differ from that, because the question is obviously not about that. What the user means is the : operator inside a variable name. I'm sorry, I don't want to annoy somebody, but your rollback makes no sense and should be reversed, but I don't want an edit-war here. Furthermore it's bash and scripting specific so why remove those tags?
    – chaos
    Oct 6, 2015 at 14:43
  • You removed TEMP and VAR variables and changed the question the way that other answers lost the meaning.
    – Pilot6
    Oct 6, 2015 at 14:46
  • @Pilot6 In my answer I don't refer to a VAR variable. But, however, you're free to change that one thing back. I wanted to make the question more general, less specific. It was never meant to sabotage other answers.
    – chaos
    Oct 6, 2015 at 14:48
  • 2
    @SnakeDoc no, it's on-topic all right
    – muru
    Oct 6, 2015 at 20:57

3 Answers 3

20

This is variable expansion and works like this (notice this is only bash and ksh specific and will not work in a POSIX shell):

$ x=1234567890
$ echo ${x:3}
4567890
$ echo ${x:7}
890
$ echo ${x:3:5}
45678

  • ${var:pos} means that the variable var is expanded, starting from offset pos.
  • ${var:pos:len} means that the variable var is expanded, starting from offset pos with length len.
6
  • Woks in zsh too
    – kos
    Oct 6, 2015 at 12:38
  • 2
    @kos It's not worth mentioning, because everything works in zsh =) I made a diet script in zsh and lost 10kg in 1 week.
    – chaos
    Oct 6, 2015 at 12:45
  • zsh for sure makes you dumber at typing paths when you're not using it :)
    – kos
    Oct 6, 2015 at 12:57
  • 1
    @kos Hehe, It's a bit like jquery: meta.stackexchange.com/a/19492
    – chaos
    Oct 6, 2015 at 13:00
  • 1
    Ha, I love how the only answer attempting to really answer the question got -2 because of "not enough jQuery"! :)
    – kos
    Oct 6, 2015 at 13:05
7

in bash it cuts away the first 3 characters of a (string) variable:

$ VAR="hello world"
$ echo ${VAR:3}
lo world

have a look at 'substring extraction' here: http://www.tldp.org/LDP/abs/html/string-manipulation.html .

2

This operator cuts off the first 3 characters of variable TEMP and assigns the rest to variable VAR.

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.