Please create an account to participate in the Slashdot moderation system

 



Forgot your password?
typodupeerror
For the out-of-band Slashdot experience (mostly headlines), follow us on Twitter, or Facebook. ×
User Journal

joke_dst's Journal: Bash variable handling 1 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'

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...

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"

Computer Science is the only discipline in which we view adding a new wing to a building as being maintenance -- Jim Horning

Working...