[wellylug] yet another simple super basic bash question

Michael Robinson michael at diaspora.gen.nz
Wed Dec 22 22:52:36 NZDT 2004


> The shell itself (especially if it's bash or ksh or similar) also has a
> lot of useful built-ins that can be used in various ways to manipulate
> text.  (People who do a lot of embedded Unix/embedded Linux development
> seem to know them off by hand.)  "man bash" can be useful for finding
> out about those builtins, although beware some of them are bash
> extensions rather than part of the Bourne shell (sh).

As proof of this, the following (bash specific) script will print "4321":

    num=1234
    num_len=${#num}
    result=''
    until [ $num_len = 0 ]
    do
	num_len=$(($num_len - 1))
	result="$result${num:$num_len:1}"
    done
    echo $result

or, more cryptically:

    num=1234
    for ((i=${#num}-1; i > -1; i--)) 
    do
	result="$result${num:$i:1}"
    done
    echo $result

I think I prefer rev(1).
    -- michael.




More information about the wellylug mailing list