• Welcome to Overclockers Forums! Join us to reply in threads, receive reduced ads, and to customize your site experience!

/bin

Overclockers is supported by our readers. When you click a link to make a purchase, we may earn a commission. Learn More.

SickBoy

Inactive Moderator
Joined
Jan 13, 2001
Location
Minneapolis, MN
As requested, here is your sticky for trading scripts.

**CAVEAT EMPTOR: Use these scripts at your own risk. Minimal knowledge of shell/perl scripting should be considered a prerequisite to using these scripts. Know what the script is doing before you run it on your system!!**

The staff and administration of overclockers.com and forum.oc-forums.com cannot be held responsible for the content or adverse effects resulting from the execution of any script posted here.

Some general rules:
1. Post ONLY scripts that you have authored OR that you have permission to repost. If you do not have permission to repost script content from a different author, links are permitted. Please observe intellectual property ideals here.

2. Post scripts as text file attachments. I know extension doesn't matter in Linux but please post them here as attachments with .txt extensions.

3. No chitchat in this thread. Will be deleted upon sight. If you have questions about a particular script, conduct them over PM, email, IM, etc... NOT here.

4. If you author a script and post it, be prepared to deal with questions/issues about it.

5. Moderator's/Admin's word is gold here. UnseenMenace, SpeeDj and I all hang out in this forum and if we see fit that new rules need to be made, we reserve that right. Other mods may come in from time to time and deal with issues should there be any. This sticky is a privilege. Respect it, and we will respect you.

That being said.... let the script sharing begin!
 
PATH

Getting Started...

A *nix OS searches certain directories to find programs/commands/scripts everytime you use the command line. These are by convention generally /bin /sbin /usr/bin /usr/sbin /usr/local/bin... etc you get the idea... /bin's or /sbin's. The list of locations for this search is called the PATH variable, and each user's PATH can be slightly different. For instance, root generally has access to some commands that regular users don't.

The first thing I recommend is to make your own directory for scripts in /home/yourusername. Call it what ever you like. I usually call mine /home/arkaine/bin

Then run this command to add your new script directory to your PATH variable. This usually works, but it depends on your shell. You could also manually edit your /home/username/.bashrc file to add or remove locations from your PATH.

PATH=$PATH:/home/your_user_name/your_script_directory
For my system, I'd run:
PATH=$PATH:/home/arkaine/bin

Now any executable script you make inside your user's own personal /bin will work from the command line as if it were a standard command.


Its a good idea to check make sure you don't accidentally name a script you create the same as an already existing command.

ex: you want to make a script called ncftp, little do you know ncftp already exists on your system...

So run this anytime you feel like whipping up a new script and want to make sure that name isn't already being used:

which name_of_script_you_want_to_make

or in this example:

which ncftp

If nothing is returned when you run that command, then you're safe. If it returns a directory path, then a command by that name already exists.
 
Last edited:
Lexicon

At the beginning of any script there is a line that calls a certain shell or interpreter for the script.

#!/bin/sh - calls the Bourne shell
#!/bin/bash - calls the Bourne Again Shell
#!/bin/perl - calls perl to interpret the script
and so on..

Different shells require slightly different syntax, and things like perl are very different from shell scripts.

Here's a linux term for you-
The #! is called a "sheh-bang"

I'm pretty sure we'll mostly be dealing with #!/bin/sh in here, since its universal to any *nix system. Maybe a little perl or python as well....
 
Last edited:
well since, this has only gotten 2 replies ill ad my script, the one and only lol


well its a very basic script , that restarts the samba daemons, after i make changes to the config files

#! /bin/bash
killall -HUP nmbd
killall -HUP smbd



thats it rofl

but anyway, this is how i made it if you know little about scripts like me


i did


vim restart.sh

that will make a new file called restart.sh

theni just put the script in there

then i saved it

ESC,:wq

then i had to change the ... cant remember the word for it... ok well im ... well anyway, i had to change the access to the file

i did chmod 700, so only root can run it/edit it
 
some folding-lovin

The foldon script will start your client. You need to make sure that the script's variable $FoldDir corresponds with your folding directory. You need to:
chmod ugo+x foldon

script and may want to:
chown username foldon

it also. Ideally you don't want folding started by root. I put mine in /usr/local/bin in this example.

Now in an /etc/rcfile (rc.local is pretty good for most distros). enter a line like this:

su -c "/usr/local/bin/foldon" username

That line will launch the foldon script under whatever username you set at boot-time.

You should start the client manually first, by:

cd /your/folding/dir
chmod ugo+x FAH3Console-LinuxB.exe
./FAH3Console-LinuxB.exe -advmethods -forceasm

That way you can fill out the user information for the config file. Once you have a client.cfg file, the scripts will take care of the rest.

killall -15 FAH3Console* is a safe way to close the client.


PS- the scripts run folding in the background, so you have to use top to see that its running, or:
more /your/folding/dir/FAHlog.txt | tail -15
to see the bottom of the log file
 

Attachments

  • foldon.txt
    297 bytes · Views: 383
Last edited:
Here's a little bash script that I wrote to run hdparm testing five time. The point of this script was to save time by not having to write each command seperated by a semicolon to get it to work. This script will be useful to all those people who like to tweak their harddrive preformance by using hdparm.

#!/bin/bash
for i in 1 2 3 4 5
do
hdparm -Tt /dev/hda
done


You can call is whatever you want, I call it hdtest, and chmod it to be executable and only run by root, since hdparm can only be run by root.
 
Here's one I wrote to make looking through filenames in a certain set of directories faster. I called it grepDex. The only major assumption is that your files have useful names.
In this case, it looks through, /mnt/raid/music/2000, /mnt/raid/music/2001, /mnt/raid/music/2002, and /mnt/raid/music/2003.
You could hack this to index your entire system if you really wanted, but building the index might take a little while. ;)
Make sure to change the for loop and $files if you use this.

If you run it looking for a file and it doesn't find the index where it expects to, it will build the index and look for the file. If you want to force it to rebuild the index, use grepDex r. Otherwise, just use grepDex searchString.


If you have any questions or issues with this script, you can chat with me via MSN at ideamagnate AT hotmail DOT com.

Code:
#!/bin/bash
musDex=~/musDex                 #where the index is
files=/mnt/raid/music/200       #where the files to be indexed are
                                                                                            
if test $# -ne 1                #if the number of args != one...
    then
        echo $0: argument missing
        exit 1                  #non-zero exit codes mean an error occured
fi
if test -f $musDex && test $1 != "r"
#if musDex exists and we don't want to force a rebuild of the index...
    then
        grep $1 $musDex|less    #do the actual search
    else
        rm -f $musDex>/dev/null #silently kill the old index
        echo rebuilding index...
        for a in [0123]         #do this with $a = 0 1 2 and 3
        do
            tree $files$a -f >>$musDex # >> appends the output so the original file isn't overwritten
        done
        echo done rebuilding index.
    if test $1 != "r"           #if arg 1 isn't "r"
        then
            grep $1 $musDex|less
    fi
fi
 
Last edited:
THIS IS SOMETHING THAT NOBODY SHOULD BE WITHOUT:
a script to give you random great names for rock bands from Dave Barry's site. :D I'll kill anyone who asks for more comments.

Please note: you'll probably have to change the ^M at the end of the really long line. In your favorite editor, press <ctrl-v>,<ctrl-m> to type it correctly. The script will do strange things otherwise. I know this from extensive personal experience. :rolleyes:

edit: Please drop me a PM if you find this useful or amusing. I'd like to know if I should keep posting here or if everyone's ignoring this thread.

If you have any questions or issues with this script, you can chat with me via MSN at ideamagnate AT hotmail DOT com.

Code:
#!/bin/bash
#Great Names for Rock Bands (thanks to Dave Barry)
#this is where the file from Dave Barry's site will go so we don't download it unnecessarily
gnrb=~/.gnrb.html
                                                                                                       
#Problems:
#this script will miss some quotes because of inconsistant html coding
  #getting them means a lot of extra effort without meaningful results
  #if someone has the time and sends me a fix, I'll be glad to edit this post
                                                                                                       
                                                                                                       
#get the file and put it into ~/.gnrb.html,
#but only if there isn't already a ~/.gnrb.html file
if ! [ -f $gnrb ]
then
  wget -q [url]http://www.davebarry.com/rockbandlist.html[/url] -O $gnrb
fi                                                                                                        
#use $() to make the output of $(command) be what the script sees
#  on all lines of the html file that have a bunch of spaces, some letters and spaces then some form of <br>, (awk selects these lines)
#    replace double spaces with nothing (ie delete),
#    replace " <BR>", "<br>" etc. with nothing (ie delete),
#    replace all remaining spaces with +++ (to make array processing easier)
#    replace ^M with nothing to keep the array from acting crazy
#the result is that dbArray is an array of gnrbs where spaces are separated by +++
dbArray=( $(cat $gnrb|awk '/^[ ]*[a-zA-Z -]*<[BRbr]*\>/ {print $0}' 2>/dev/null|sed -e 's/  //g' -e 's/[ ]*<[brBR]*>//' -e 's/ /+++/g' -e 's/^M//g'))
                                                                                                       
#pick a random number to figure out which gnrb to use
index=`expr $RANDOM \* ${#dbArray[@]} / 32676`  # 32676 is the largest number $RANDOM can be
                                                                                                       
#make sure that we don't return an empty gnrb
while ! [ ${dbArray[$index]} ]  #testing a string returns true if it's non-empty
do
  index=`expr $RANDOM \* ${#dbArray[@]} / 32676`
done
                                                                                                       
#print it and take care of the +++ in the gnrb
echo ${dbArray[$index]} would make a great name for a rock band.|sed -e 's/+++/ /g'
 
Last edited:
Am I the only one here who writes scripts, or are mine just so bad that nobody else wants to be associated with this thread?

Anyway, here's one that has to be run as root that makes sure that a certain amount or percentage of your RAM is free.
Run freeram 10 to make sure 10MB are free and run freeram 10% to make sure that 10% of your ram is free.

The script works by making a ramdisk of the specified size, filling it up with a file dd'd from /dev/zero, then unmounting the ramdisk and rmmoding the ramdisk driver. You need to have ramdisk support compiled as a module to run this.

Right now, you can tell the script to free more ram than you have and it will try to. I wrote this script with good intentions and will use it myself, but I can't be responsible for what it does to your computer, especiually if you tell it to do something stupid.


If you have any questions or issues with this script, you can chat with me via MSN at ideamagnate AT hotmail DOT com.

Code:
#!/bin/bash
#a script to ensure that a certain amount of RAM is free
                                                                                                     
ramDir=/mnt/ram #the dir where the ramdisk will be mounted
ramDev=ram0     #name of the ram device (in case you already have one)
fsType=ext3     #filesystem of the ramdisk (inconsequential)
                                                                                                     
ramTotal=$(cat /proc/meminfo|awk '/MemTotal/ {print $2}')
ramPercent=$(echo $1|grep '%'|sed 's/\%//')
                                                                                                     
if ( test "$ramPercent" == "" )
then
  echo freeing $1 MB of ram
  let "rdSize= $1 * 1024"
else
  echo freeing $ramPercent% of total ram
  let "rdSize = ( $ramTotal * $ramPercent ) / 100"
fi
                                                                                                     
cat /proc/meminfo|awk '/MemFree/ {print "currently " $2 " " $3 " free"}'
                                                                                                     
if ( ! insmod rd rd_size=$rdSize >/dev/null )
then
  echo error: rd module insertion failed
  echo please compile ramdisk support as a module
  echo in menuconfig, go to "Block devices" -> "RAM disk support"
  exit 1
fi
mkdir $ramDir >/dev/null 2>/dev/null
mkfs.$fsType /dev/$ramDev >/dev/null 2>/dev/null
mount /dev/$ramDev $ramDir
dd if=/dev/zero of=$ramDir/random >/dev/null 2>/dev/null
umount $ramDir
rmmod rd
                                                                                                     
cat /proc/meminfo|awk '/MemFree/ {print "currently " $2 " " $3 " free"}'
 
Last edited:
Some more of mine

My script for folding in wine with the windows client. make sure to set the variable $FoldDir and also make sure your windows folding client is named correctly and is executable.

It does a lot of little things aside from starting wine. For instance, it will kill other instances of folding before it starts and deelte fah_cores in case you had previously folded with a linux client in the same directory (not good for duallies, sorry). It also wgets the client from stanford or tries to copy it from /usr/local/bin (where I keep my clients) if its unable to download the client.
 
Last edited:
I wrote this little script to turn off the screen when the lid of my lappy closes in debian. You must have a radeon vid card and it assums that your lid state is in that spot. If not you must change that line or two. Changing the sleep will effect the delay between the screen changing. I just made this load with the other rc scripts and makes life easier. I have found the max cpu it used on my lappy to be .03 everyonce in a while.

Code:
#!/bin/bash
sleep 2
x=1
oldstate=$(echo `cat /proc/acpi/button/lid/LID/state | awk '/state:/{print $2}'`)

until [ "x" = "0" ]; do
	newstate=$(echo `cat /proc/acpi/button/lid/LID/state | awk '/state:/{print $2}'`)

	if [ newstate != oldstate ]; then
		if [  "$newstate" = "closed" ]; then
			radeontool light off
			oldstate=$newstate
		fi
		if [ "$newstate" = "open" ]; then
			radeontool light on
			oldstate=$newstate
		fi
	fi

	sleep 5
done
exit 0

Jon
 
OK, here is my first contribution to the script thread. It's a bash script I wrote to start the Half Life dedicated LAN server for HL or any of the mods.

It launches everything in the background and pipes the output to a logfile in <HLDS Install dir>/logs which is uniquely named with the game name and a fudged timestamp.

To launch it, you pass the game name and a map name, e.g.

./server_start cstrike de_aztec

or

./server_start dod dod_anzio

To use it, you'll obviously have to change the applicable directory locations and (maybe) create a logs directory under your HLServer install directory.
 

Attachments

  • server_start.txt
    436 bytes · Views: 352
Recycle Bin

Hey all. I made a "recycle bin" script (bash). It is acutally 4 scripts, and I think it is a bit big to post up here, so here is the download link. It comes with an installer too :)

http://www.angelfire.com/bug/tix/recycle_bin.tar.gz

(just to let u know, my normal screen name is tix for everything else, this account (O/C account) is just old)

It is pretty decent and I use it all the time.
It is all command line, but I added support for it in my file browser (rox), you can too if you know enough about your browser. features:
recycle ("recycle" file), this moves the file to the bin, when it does though it also stores the original path, compresses the "recycled" file to save space. Both the path and the compressed file are hidden in the recycle bin, but a script with the same name as the original file is created in the bin as well. When this script is run it gives you the option to restore, or delete the file. You can also do this manually.
It also restores or deletes the file.

How to use:
Uncompress the file and install:
Code:
tar -zxvf recycle_bin.tar.gz
cd ./recycle_bin
./install.sh
then to see how to use just:
Code:
recycle -h
This will bring up the help message, and shows how to use it.
 
I use this one often on my fileserver. It's called ws for "what started...", and it prints out the PID, starting command, the cwd and the memory use of any processes that match its first parameter. It's very useful for keeping an eye on daemons.
example:
ideamagnate@Fornifax ~ $ ws thunder
6978: /bin/bash /usr/bin/thunderbird
/home/ideamagnate
5132 kB
6984: /usr/lib/MozillaThunderbird/thunderbird-bin
/home/ideamagnate
74320 kB
6989: /usr/lib/MozillaThunderbird/thunderbird-bin
/home/ideamagnate
74320 kB
6990: /usr/lib/MozillaThunderbird/thunderbird-bin
/home/ideamagnate
74320 kB
7018: /usr/lib/MozillaThunderbird/thunderbird-bin
/home/ideamagnate
74320 kB



Code:
#!/bin/bash
PSAUX=~/.psauxtmp
ps aux>$PSAUX
for ps in $(pgrep $1)
do
  #the format of ps' output is "root  ... 0:00 [nfsd]"
  #Strip out everything before the name of what was executed by looking for
  #the last time mentioned (ie 0:00)
  echo -n $ps": " && cat $PSAUX | grep $ps | sed -r 's;.*[0-9]+:[0-9]+ ;;g'
 
  #get the cwd by looking at /proc/$ps/cwd
  echo "        "$(file /proc/$ps/cwd | sed -e "s/.*\ \`//g" -e "s/'//g")
   
  #get the memory footprint by grepping /proc/$ps/status
  echo "        "$(cat /proc/$ps/status | grep VmSize | sed -e 's/.*  //g')
done
rm $PSAUX

Also available here.
 
This one is probably my favorite: an non-interactive OC Forums sig generator!
You can find the code here.

Just download and run mksig (don't forget chmod u+x mksig). It will make ~/.mksig, and put all its important files there. The central file is ~/.mksig/sigmkr. This is run by mksig and determines what your sig will look like. If you put "date" into ~/.mksig/sigmkr, your sig will contain the date it was submitted. If you put "fortune -o", you'll get banned from the forums, etc. mksig creates a default sigmkr that uses fortune -s and date when it's first run, but if the file exists mksig will run it without changing anything. The reason for making sigmkr a separate file is debugging: you can run sigmkr directly to see what your sig would look like, and it won't effect your forums sig.
It will also as for your login info, which it will store in its dir. (It stores passwords as md5sums, which is all vb3 cares about anyway). It echoes your password as you type it, but clears the screen as soon as you're done. I'm open to more elegant solutions.
ATM, it doesn't save your previous sig, so make sure you have it backed up.
Finally, all sigs generated are stored in sig.log, along with the time and date they were submitted so you know what people have been seeing.

I'll help people get this working if they can't get the default sig up, but you're on your own for customizing your sig. Here's a link to the Advanced Bash Scripting Guide. Lots of info and very useful. Don't miss section 32.

edit: This script needs wget 1.9 or higher. It automatically detects if the version is high enough, but I though I shouldn't let it suprise anyone.

edit2: If you like mksig or would like to see some feature, feel free to PM me about it. I mostly made this for myself and made the code fit for public consumption as an afterthough, but it'd still be encouraging to know that someone else likes it.

Enjoy.
 
Last edited:
Smart Backup Script

This script will copy any files updated in the last 24 hours to a backup drive mounted at /mnt/huge. It won't copy from imaginary filesystems, like /proc, /sys, and /dev, or from anything in /mnt (mostly just to avoid copying itself into itself). It will also leave alone anything that has "nobackup" in its path.

Code:
#!/bin/sh

if [ `mount | grep '/mnt/huge' | wc -l` -eq 0 ]; then
        echo "Nothing is mounted on /mnt/huge!"
        exit
fi

find / -mtime -1 -type d | egrep -v ^'/sys' | egrep -c ^'/proc' | egrep -v ^'/dev' | egrep -v ^'/mnt' | grep -v 'nobackup' > ls-list.txt
for DIR in `cat ls-list.txt`
do
	if [ ! -d /mnt/huge$DIR ]; then
		mkdir /mnt/huge$DIR
	fi
done

find / -mtime -1 -type f | egrep -v ^'/sys' | egrep -v ^'/proc' | egrep -v ^'/dev' | egrep -v ^'/mnt' | grep -v 'nobackup' > ls-list.txt
find / -mtime -1 -type l | egrep -v ^'/sys' | egrep -v ^'/proc' | egrep -v ^'/dev' | egrep -v ^'/mnt' | grep -v 'nobackup' >> ls-list.txt
for FILE in `cat ls-list.txt`
do
	cp -a $FILE /mnt/huge$FILE
done

rm ls-list.txt
 
Here's a simple perl NFS mounter script that I use for my laptop. Since I use it in a handful of different places, I don't really want to hard mount any NFS stuff in /etc/fstab or set up the automounter.



Code:
#!/usr/bin/perl

# Perl to mount NFS mounts for home network

my $rc1 = "";

print "\nMounting /mnt/downloads...\n";
$rc1 = system ("mount -t nfs blur:/mnt/raid/downloads /mnt/downloads");
checkMount ();

print "\nMounting /mnt/mp3...\n";
$rc1 = system ("mount -t nfs blur:/mnt/raid/mp3 /mnt/mp3");
checkMount ();

print "\nMounting /mnt/docs...\n";
$rc1 = system ("mount -t nfs blur:/mnt/raid/docs /mnt/docs");
checkMount ();

print "\nMounting /mnt/www...\n";
$rc1 = system ("mount -t nfs blur:/mnt/raid/www /mnt/www");
checkMount ();

print "\n\nNo more mounts to perform. Exiting.\n";

sub checkMount {
        print "Mount returned $rc1\n";
        if ($rc1 == 0) {print "Mount Successful!\n\n"; }
        else {die "Mount may not have worked. No more mounts will be attempted\n";}
}
 
Here's another Perl script. It's a crime that I didn't learn Perl earlier. It's so much fun to hack in.
This script parses through the output from lsof and gives you a nice ordered list of all processes and how many files they each have open, plus the total. Note that you'll get a different result running as root vs another user and that long process names are truncated. It's that way in the output from lsof.

Code:
#!/usr/bin/perl -w
 
my $fileName;
open(LSOF,"/usr/sbin/lsof |");
<LSOF>;
while(<LSOF>) {
  ($fileName = $_ ) =~ s/([^\s]*).*/$1/;
  chomp($fileName);
  $nameHash{$fileName}++;
  #print "added 1 to $fileName\n";
}
close(LSOF);
 
my $total;
foreach $name (sort { $nameHash{$a} <=> $nameHash{$b} } keys %nameHash) {
  print "$nameHash{$name} - $name\n";
  $total += $nameHash{$name};
}
print "total: $total\n";
 
here´s one that i use for my dual monitor setup in gentoo since i don´t have kde or gnome installed. it works provided you have xv and imagemagick installed.

#!/bin/bash
convert -size 1152x864 $1 -resize 1152x864 f1.jpg
convert -size 1152x864 $2 -resize 1152x864 f2.jpg
convert +append f1.jpg f2.jpg wallpaper.jpg
rm f1.jpg
rm f2.jpg

xv -root -max -quit wallpaper.jpg


change the screensize to what you need and find two wallpapers you want and you´re good to go. ./scriptname image1.jpg image2.jpg and you´ll get two full size images, one on each monitor. enjoy.
 
I wrote this one because I wanted to copy my music from my old hard drive to my new yoper install, but the cp command can't handle the amount of files I have.

Just modify SourceDir and DestDir to be whatever you want. If you use .ogg's or .wma's or whatever else, just change Extension to whatever you want.

The script should check to see if a file already exists there, and if it does, it checks to see if it's older than the one being copied. If the one being copied is newer, the old one is overwritten, but if the one being copied is same age or older, no action is taken.

And don't panic if it says "cp: cannot stat `/mnt/hdd3/music//0*.mp3': No such file or directory" or something like that, it just means that there are no files in that director y that start with that letter.

Code:
 #!/bin/bash
SourceDir=/mnt/hdd3/music/
DestDir=/music/
Extension=mp3
for a in 0\* 1\* 2\* 3\* 4\* 5\* 6\* 7\* 8\* 9\* A\* B\* C\* D\* E\* F\* G\* H\* I\* J\* K\* L\* M\* N\* O\* P\* Q\* R\* S\* T\* U\* V\* W\* X\* Y\* Z\* a\* b\* c\* d\* e\* f\* g\* h\* i\* j\* k\* l\* m\* n\* o\* p\* q\* r\* s\* t\* u\* v\* w\* x\* y\* z\*
do
  cp -uf $SourceDir/$a.$Extension $DestDir
done
exit 0
 
Last edited:
Back