Find the answer to your Linux question:
Results 1 to 2 of 2
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    Bittorrent Script Query


    Hi All,

    I'm not a programmer and wish to query some of the below code, which is
    the only part I don't understand.


    Code Being Queried:

    Code:
    BEGIN { srand() }
    	{ names[NR]=$0 }
    	END {
    	    j=int(NR*rand());
    found here,

    http://lue.dyn.dhs.org/2005/20050708135201.html

    Full Code:

    Code:
    #!/bin/sh
    #bt.offer: circulate offered torrents
    
    howmany=0
    offerall=0
    loopctrl=0
    
    case $1 in
        all) offerall=1 ;;
        [0-9]*) howmany=$1 ;;
        "") howmany=7 ;;
    esac
    
    # first, remove what's already being offered 
    cd /usr/local/bt || exit 1
    if [ -f $HOME/.bt/offer/offered ]; then
        rm $(cat $HOME/.bt/offer/offered)
        rm $HOME/.bt/offer/offered
    fi
    
    # two special cases
    #1): remove all offered torrents
    if [ $howmany -eq 0 ]; then
        exit 3
    fi
    #2): offer all the torrents that I have
    if [ $offerall -eq 1 ]; then
        cd $HOME/.bt/offer || exit 2
        ls *.torrent > offered
        cp *.torrent /usr/local/bt/
        exit 0
    fi
    
    # offer another batch 
    cd $HOME/.bt/offer || exit 2
    i=0
    while [ $loopctrl -eq 0 ]  
    do
        torrent=$(ls *.torrent |
        awk '
    	BEGIN { srand() }
    	{ names[NR]=$0 }
    	END {
    	    j=int(NR*rand());
    	    if (j<1) j=j+10;
    	    if (j>NR) j=NR;
    	    print names[j]
    	}
        ' )
        echo "$torrent" >> offered
        i=$(expr "$i" + 1)
        if [ $i -ge $howmany ]; then
    	loopctrl=1
        fi
        sleep 1s
    done
    sort offered | uniq > /tmp/$$
    mv /tmp/$$ offered
    for torrent in `cat offered`
    do
        cp "$torrent" /usr/local/bt/"$torrent"
    done
    Mod edit - Added code tags
    Last edited by Dolda2000; 01-22-2006 at 03:16 AM.

  2. #2
    Linux Guru
    Join Date
    Oct 2001
    Location
    Täby, Sweden
    Posts
    7,578
    It seems that that awk script reads a list of file names, chooses one of them at random, and prints it.
    More exactly, "BEGIN { srand(); }" seeds the random number generator. "{ named[NR] = $0 }" runs once for each line of input to awk, and adds that line to an array, in order to store all the file names in a contiguous array. The command block marked by "END" generates a random number between zero and NR (NR is the number of records read by awk), looks up the item in the array that is indexed by that number, and prints the result.

    The random number code does definitely look really unelegant, but it's not as if it doesn't work.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •