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


Forgot your password?
DEAL: For $25 - Add A Second Phone Number To Your Smartphone for life! Use promo code SLASHDOT25. Also, Slashdot's Facebook page has a chat bot now. Message it for stories and more. Check out the new SourceForge HTML5 Internet speed test! ×
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}
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"

Sendmail may be safely run set-user-id to root. -- Eric Allman, "Sendmail Installation Guide"