×

Welcome to the Slashdot Beta site -- learn more here. Use the link in the footer or click here to return to the Classic version of Slashdot.

Thank you!

Before you choose to head back to the Classic look of the site, we'd appreciate it if you share your thoughts on the Beta; your feedback is what drives our ongoing development.

Beta is different and we value you taking the time to try it out. Please take a look at the changes we've made in Beta and  learn more about it. Thanks for reading, and for making the site better!

Bash variable handling

joke_dst (832055) writes | more than 6 years ago

User Journal 1

Since I still haven't found any comprehensive source for how the evil variables in bash can be truncated, clipped and so on so here's a short list for me mostly:

VAR=hello in all examples

String length: ${#VAR}
ex:
echo ${#VAR} #yields '5'

Substring: ${#VAR:[chars to remove from start]:[chars to return]}
Last parameter can be ignored if you want to the end ("${VAR:2}")
ex:
echo ${VAR:1:3} #yields 'ell'

Since I still haven't found any comprehensive source for how the evil variables in bash can be truncated, clipped and so on so here's a short list for me mostly:

VAR=hello in all examples

String length: ${#VAR}
ex:
echo ${#VAR} #yields '5'

Substring: ${#VAR:[chars to remove from start]:[chars to return]}
Last parameter can be ignored if you want to the end ("${VAR:2}")
ex:
echo ${VAR:1:3} #yields 'ell'

Remove last character: ${VAR%?}
ex:
echo ${VAR%?} #yields 'hell'

Return last character: ${VAR:${#VAR}-1}
Bit messy, best I could find though
ex:
echo ${VAR:${#VAR}-1} #yields 'o'

To be continued...

1 comment

Technically...... (1)

Qzukk (229616) | more than 6 years ago | (#22002160)

echo ${VAR%?} #yields 'hell'


Specifically, % removes the matching substring from the end of the variable, so in this case, "?" matches any single character.

% is very useful for batch processing of files, especially when you want to have output filenames with a different extension:

for x in *.jpg; do process --input $x --output ${x%jpg}gif; done

The opposite is #. For instance, in your case, echo ${VAR#?} would produce "ello"
Check for New Comments
Slashdot Account

Need an Account?

Forgot your password?

Don't worry, we never post anything without your permission.

Submission Text Formatting Tips

We support a small subset of HTML, namely these tags:

  • b
  • i
  • p
  • br
  • a
  • ol
  • ul
  • li
  • dl
  • dt
  • dd
  • em
  • strong
  • tt
  • blockquote
  • div
  • quote
  • ecode

"ecode" can be used for code snippets, for example:

<ecode>    while(1) { do_something(); } </ecode>
Sign up for Slashdot Newsletters
Create a Slashdot Account

Loading...