Forgot your password?
typodupeerror
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}
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"

Nothing is impossible for the man who doesn't have to do it himself. -- A.H. Weiler

Working...