Last Updated: February 25, 2016
·
689
· natfriedman

bash string tricks

You can use ${} braces in bash to take substrings of variables:

${var:offset:length}

For example:

~$ str="anemone"; echo ${str:1:4}
nemo

This is incredibly useful! And you can actually do shell arithmetic in the offset and length parameters, too. So for example, ${var:i+1:a-3}

And to find the length of a string, you can use:

${#str}

So

str=”foobar”; echo ${#str}

will print “6″