Doing for loops in bash

9. May 2012 23:21

 

It can be commonly known that you can do for loops in bash by doing something like for i in * ; do echo $i ; done or some such. This will loop for every file in the current directory. Though typical for loops for a specific number range can be a little more difficult since you need to form the data to be able to execute the loop.

 

To get a simple for loop to work we can copy python's for i in range(x, y): type of loop since the bash for loop is exactly the same as this. Both bash / python perform a for each loop around a list of data items rather than the traditional for loop with a counter. This can be used to our advantage since all you need to do is create a small program that generates this data lists.

 

The following c program does this.

 

#include <stdio.h>
#include <stdlib.h>

void print_usage(FILE *fp, char *app) {
    fprintf(fp, "Usage: %s <start number> <end number>\n", app);
    fprintf(fp, "\n");
}

int main(int argc, char **argv) {
    int a = 0, b = 0;
    int i;

    if (argc < 3) {
        print_usage(stderr, argv[0]);
        exit(EXIT_FAILURE);
    }

    a = atoi(argv[1]);
    b = atoi(argv[2]);
    
    if (a >= b) {
		int tmp = a;
		b = a;
		a = tmp;
    }

    for(i=a;i<=b;i++) {
        printf("%d\n", i);
    }

    return 0;
}

All you need to do is put the program above into a c file and compile it with gcc (gcc -Wall range.c -o range) and place the executable on the path (eg in $HOME/bin). Then you can do for loops in the bash shell the following way.

 

for i in `range 0 20` ; do echo $i ; done

The above will of course produce the output of 0 to 20 on the terminal when run.

 

E-mail Kick it! DZone it! del.icio.us Permalink


Adding emergency swap space to linux

6. January 2012 06:00

 

This is a quick guide to adding emergancy swap space to linux. Which is useful when you know a machine is going to run out memory. Or you need a lot of memory for a single task that cannot be completed without the extra memory.

 

Step 1

 

Login as root

 

Step 2

 

Create a new file of the size that you want to add using the following command. In this case 512 mbytes of space.

 

dd if=/dev/zero of=/extraswap1 bs=1024 count=512k

 

Step 3

 

Fix the permissions on the file so that only the creator can read / write to it.

 

chmod 0600 /extraswap1

 

Step 4

 

Turn it into a swap file and tell linux to turn on the extra space

 

mkswap /extraswap1

swapon /extraswap1

 

Step 5

 

If you want the swap to be enabled after the next reboot of the machine you will need to add the following line to /etc/fstab

 

/extraswap1 swap swap defaults 0 0

 

Finally

 

You can verify that it is working by either using free or by looking directly at the proc filesystem using cat /proc/swaps

E-mail Kick it! DZone it! del.icio.us Permalink