Catch up on stories from the past week (and beyond) at the Slashdot story archive

 



Forgot your password?
typodupeerror
×
User Journal

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

"I've seen it. It's rubbish." -- Marvin the Paranoid Android

Working...