[clug] Rosetta code: bash/bourne shell 'loops' example

steve jenkin sjenkin at canb.auug.org.au
Sat Mar 20 22:35:12 MDT 2010


Anyone care to comment or offer some more solutions?
(including your favourite shell)

I found their nested 'for loop' examples awkward...

cheers
steve

----------------------------
The 'loops' language comparison.
Print this (i.e. for n=5)

*
**
***
****
*****

A shell solution using compare strings. (works for n = 32k at least.)
----------------------------
n=5
 l=$(yes '*' |head -${n}|tr -d '\n')
 s='';

until [[ "$l" = "$s" ]]
do
  s="${s}*"
  echo "$s"
done
----------------------------

An alternate using 'for ( ; ; )' and subscript '${Var:start:len}' :
----------------------------
n=5
 l=$(yes '*' |head -${n}|tr -d '\n')

for (( i=1; $i - ($n + 1); i=$i + 1))
do
  echo "${l:0:${i}}"
done

----------------------------

<http://rosettacode.org/wiki/Loops/For#UNIX_Shell>

UNIX Shell
Works with: Bourne Again SHell version 3

for (( x=1; $x<=5; x=$x+1 )); do
  for (( y=1; y<=$x; y=$y+1 )); do
    echo -n '*'
  done
  echo ""
done
----------------------------

<http://rosettacode.org/wiki/Loops/For#UnixPipes>

UnixPipes

yes \ | cat -n | (while read n ; do
  [ $n -gt 5 ] && exit 0;
  yes \* | head -n $n | xargs -n $n echo
done)
----------------------------
-- 
Steve Jenkin, Info Tech, Systems and Design Specialist.
0412 786 915 (+61 412 786 915)
PO Box 48, Kippax ACT 2615, AUSTRALIA

sjenkin at canb.auug.org.au http://members.tip.net.au/~sjenkin


More information about the linux mailing list