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?

Looping in shell scripts
18 November 2005 @ 23:23 GMT
by Paul

In my continued attempt at getting to grips with shell scripting and, one day, even perhaps writing a shell script that does something useful, I'm writing this note about looping.

The shell 'for' goes through each item on a list in turn, exactly the same as perl really. So:

for var in 1 2 3 4 5; do
echo $var
done

will print out

1
2
3
4
5

Which is all very fascinating. Perhaps more usefully, we can use a glob to process every file in the current directly, so:

for file in *; do
echo $file
done

will list every file in the current working directory, because the '*' is expanded by bash to all files in the directory. Of course, this does the same as the 'ls' command.

Slightly more useful might be something like this:

for file in *~; do
 mv $file ~/Backups/
done

which moves all the files ending in '~' to a directory named 'Backups'.

More on loops later. In the meantime, there's a great page on it here.

Tags: bash



Leave a comment:

Are you human?