Want to read Slashdot from your mobile device? Point it at m.slashdot.org and keep reading!


Forgot your password?

Slashdot videos: Now with more Slashdot!

  • View

  • Discuss

  • Share

We've improved Slashdot's video section; now you can view our video interviews, product close-ups and site visits with all the usual Slashdot options to comment, share, etc. No more walled garden! It's a work in progress -- we hope you'll check it out (Learn more about the recent updates).

User Journal

joke_dst's Journal: Bash variable handling 1

Journal by joke_dst
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}
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}")
echo ${VAR:1:3} #yields 'ell'

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

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

To be continued...

This discussion has been archived. No new comments can be posted.

Bash variable handling

Comments Filter:
  • 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"

A formal parsing algorithm should not always be used. -- D. Gries