Gnuru.org
Productive Linux


Subscribe

 Subscribe via Feedburner in a reader

Enter your email address:

Delivered by FeedBurner


Login
Login:
Password:



Don't have an account?
Sign up to Gnuru.org
Forgot your password?

Another lame attempt to learn Bash
27 January 2006 @ 14:29 GMT
by Paul

In my continuing attempts to learn bash, I've been looking at infinite loops. Here is an example of an infinite loop:

while true
do
 echo "Hello, world"
done

This will keep printing 'Hello, world' until interrupted by something like control-c. In itself that is useless.

Below is a script that might be slightly more useful. It monitors the number of lines in a file, the file being the argument given to the script when it is invoked.

#!/bin/bash

while true
do
 LINES=`wc $1 | awk {'print $1'}`
 echo "File has $LINES lines." 
 sleep 3s
done

Note that the use of 'awk' to get the right field from the 'wc' command.

Next, I wanted to try something a little more complicated involving some arithmetic. One of the reason I don't like bash is arithmetic is so ugly! Here's an example:

#!/bin/bash

let START=`wc $1 | awk {'print $2'}` 
while true
do
 WORDS=`wc $1 | awk {'print $2'}`
 let ADDED=$(($WORDS - $START))
 echo "Total words: $WORDS. Words added today: $ADDED"
 sleep 3s
done

This simply monitors the number of words in a file from the time the script is invoked. Note the ugly arithmetic.

So that was fun! Next stop - something more difficult.




Leave a comment:

Are you human?