Home > Bash, Linux > Bash skript exempel

Bash skript exempel

Skicka epost med diskutrymme (awk, case)

awk returnerar den femte kolumnen från df.
grep -v exkluderar raden med Use
sort -n sorterar siffror i stigande ordning
tail -1 returnerar sista raden som i detta fall är det högsta talet p.g.a. sort
cut -d väljer fältavgränsare, -f1 väljer fält nr 1, minustecknet på slutet anger att hämta indatat från standard-ut-enheten (istället för från en fil).

#!/bin/bash

# This script does a very simple test for checking disk space.

space=`df -h | awk '{print $5}' | grep % | grep -v Use | sort -n | tail -1 \
| cut -d "%" -f1 -`

case $space in
[1-6]*)
 Message="All is quiet."
 ;;
[7-8]*)
 Message="Start thinking about cleaning out some stuff.  \
There's a partition that is $space % full."
 ;;
9[1-8])
 Message="Better hurry with that new disk...  One partition is $space % full."
 ;;
99)
 Message="I'm drowning here!  There's a partition at $space %!"
 ;;
*)
 Message="I seem to be running with an nonexistent amount of disk space..."
 ;;
esac

echo $Message | mail -s "disk report `date`" anny

Skicka epost när viss text finns på webbsida

wget http://domain.com/file.html
grep -w Offline file.html
if [ $? -eq 0 ]
then
 mailx -s "Offline found" user@yourdomain
fi
rm file.html

Lista bara aktiva processer

Use ps, grep for the process name, then only select the lines where the 8th field starts R or S:

ps aux | grep process | awk '$8 ~ /^[RS]/'

If you want to limit the process name search to just the first part of the command (the process name itself) and not mistakenly match one of the parameters or other parts of the “ps” output, then:

ps aux | awk '$11 ~ /'"process"'/ && $8 ~ /^[RS]/'

(careful with the quotes round “process”)

Döda alla processer för en applikation

kill `ps -A|grep myapp|awk {'print $1'}`

eller

killall myapp

Starta om Apache process automatiskt via cron

Something like the following should do, just change 127.0.0.1 to you Web servers IP and possible tweak the /etc/init.d/apache* script name:

# Every hour ensure Apache is running and responsive, else START and / or RESTART apache.

01 * * * * (((ps -ef | grep -v grep | grep -q 'bin/http') ||
 /etc/init.d/apache* start) && (wget -qO /dev/null http://127.0.0.1/ ||
 /etc/init.d/apache* restart)) 2>&1 >/dev/null

Skapa array av strängar

myarray=(`ifconfig eth0`)
mymac=${myarray[5]}

Byta mappsökvägar

Use this script to search in all your tomcat sub folders for files that contain the old folder location. Change “/old/folder/location” to the correct location, then run it in the tomcat folder.

for  i in `find ./ -type f -name "*"`; do T=`cat $i | \
 grep  "/old/folder/location"`; if [ "$T" != "" ]; then \
 echo $i; echo $T; echo  ""; fi; done

Leta filer innehållande viss text

The following lists files containing a string  ignoring case:

grep -irl STRING *

Alternate method:

grep -i "STRING" `find . -name "*.txt" -print`

Lista storleken på mappar

You can use the command df -h to check if your drives are full. Then you can use the command du -hs {directory} to check the size of a directory in the hard disk.

To check all directories from root level, get root access with su (CentOS / Red Hat), then use the command:

du -hsc /*

or

find / -maxdepth 1 -mindepth 1 -type d -exec du -hs {} \;

In Ubuntu / Debian use sudo in front of the command to get root access.

Skript för att begränsa antalet instanser av ett program

There is no built-in way in CVS to limit the number of process instances. You could help yourself with a little trick:

# rename cvs, adapt the path if necessary
 mv /usr/bin/cvs /usr/bin/cvs.bin

Create a script that will run CVS, named /usr/bin/cvs

————— >8 —————

#!/bin/bash

lockfile=/var/lock/cvs_instances.lock
max_instances=5

# get number of running instances
 if [ -r $lockfile ]; then
 num_instances=`awk '{printf $1}' $lockfile`
 else
 num_instances=0
 fi

# check if max is reached
 if [ $num_instances -lt $max_instances ]; then
 # if not, increase the number by 1
 awk '{printf("%d",$1+1)}' $lockfile >$lockfile
 # run the real cvs binary with all parameters passed to the script
 exec /usr/bin/cvs.bin "$@"
 # and decrease the number of running instances after the cvs has exited.
 awk '{printf("%d",$1-1)}' $lockfile >$lockfile
 fi

————— >8 —————

# Make sure the script has the right permissions:
chown root:root /usr/bin/cvs
chmod 0744 /usr/bin/cvs

Skript för att processa alla filer i en katalog

Skript som kopierar filer som saknas från hårddisken till en USB-pinne:

for file in ~/Documents/music/*; do 
        if [ -e /media/sdc1/"$file" ]; then
                cp $file /media/sdc1/$file
        fi
done

Ett annat exempel:

find ~/Documents/music -type f -execdir env 'file={}' \
 bash -c 'if ! test -e "/media/sdc1/$file"; then \
 cp "$file" "/media/sdc1/$file"; fi'  \;

Följande skript kodar om alla *.ogv-filer i en mapp till avi-filer.

#!/bin/bash

directory=~/Bilder/

while read file; do
 echo ”Processing: $file”
 mencoder ”$file” -ofps 23.976 -ovc lavc -oac mp3lame -lameopts abr:br=56 \
 -o ”$file.avi” done < <(find "$directory" -iname '*.ogv' -print)

Script för att packa upp alla RAR-filer i mapp

#!/bin/bash
#
if [ $# = 0 ]; then
 echo "$0 dir/"
 exit 0
fi
dirlist=$(ls -d $1*/)
dir2list=$(ls -d $1*/*/)
for d in ${dirlist} ${dir2list}; do
 echo "Thinking about $d ..."
 if [ -d "$d" ]; then
  echo "Yeah a directory"
  # First look for *.rar, to unrar
  rarcount=$(ls "${d}"/*.rar | wc -l)
  if [ $rarcount = 1 ] ; then
   echo "Unpacking rar..."
   unrar x -o- -inul "${d}/*.rar" $d
   if [ $? = 0 ]; then
    echo "OK."
    rm $d/*.r??
   else
    echo "FAILED: ${d}"
   fi
  elif [ $rarcount > 1 ] ; then
   part1rarcount=$(ls "${d}"/*.part1.rar | wc -l)
   part01rarcount=$(ls "${d}"/*.part01.rar | wc -l)
   part001rarcount=$(ls "${d}"/*.part001.rar | wc -l)     
   if [ $part1rarcount = 1 ] ; then
    echo "Unpacking rar..."
    unrar x -o- -inul "${d}/*.part1.rar" $d
    if [ $? = 0 ]; then
     echo "OK."
     rm $d/*.rar
    else
     echo "FAILED: ${d}"
    fi
   fi
   if [ $part01rarcount = 1 ] ; then
    echo "Unpacking rar..."
    unrar x -o- -inul "${d}/*.part01.rar" $d
    if [ $? = 0 ]; then
     echo "OK."
     rm $d/*.rar
    else
     echo "FAILED: ${d}"
    fi
   fi
   if [ $part001rarcount = 1 ] ; then
    echo "Unpacking rar..."
    unrar x -o- -inul "${d}/*.part001.rar" $d
    if [ $? = 0 ]; then
     echo "OK."
     rm $d/*.rar
    else
     echo "FAILED: ${d}"
    fi
   fi
  else
   echo "No rars"    
  fi # if unrar
 fi
 echo "next directory"
done
#

Kommando för att lägga till ‘noauto’ i textfil

sudo sed -i 's/ttl=5/noauto,ttl=5/' /etc/fstab

Köra kommandon för flera användare

Another (possibly more elegant) way to do this is allow the users to run a script using sudo.  Save the attached code into /bin/su-wrap and chmod it to 700.

Your sudoers file then becomes just this:
User_Alias ADMIN = a, b, c
ADMIN ALL = (ALL) /bin/su-wrap

In my case, I’m using foo1 and foo2 as “ADMIN” users, and allowing either of them to switch to the other.  You can change the 2nd lline of the su-wrap script to list whatever users you want your admins to be able to su over to.  Using your example, you’d put:
ALLOWED_USERS=”functional1

functional2″.

Testing:
foo1@npx1600734:~ $ sudo su-wrap – foo2
Password:
Executing: /bin/su – foo2
foo2@npx1600734:~ $ exit
foo1@npx1600734:~ $ sudo su-wrap foo2
Executing: /bin/su foo2
foo2@npx1600734:~ $

#!/bin/sh
ALLOWED_USERS="foo1 foo2"
USING_ENV=0
if [ "$1" = "-" ]; then
  USING_ENV=1
  shift
fi
if [ $# -ne 1 ]; then
  echo "Usage: su-wrap [-] username" >&2
  exit 1
fi
for i in $ALLOWED_USERS; do
  if [ $1 = $i ]; then
    if [ $USING_ENV -eq 1 ]; then
      CMD="/bin/su - $i"
    else
      CMD="/bin/su $i"
    fi
    echo "Executing: $CMD"
    $CMD
    break
  fi
done

To automatically check if the IP’s changed

You can add a check script and run it with cron. To add an entry to cron, use (run it as root):

# crontab -e

To check the IP every hour, you can use (first press “i” to enter INSERT mode in vi):

0 * * * * /root/chkip.sh

Then save the file (ESC and the keys “:wq” + ENTER).

Create the script with

# vi /root/chkip.sh

and paste in the attached code.

After this you’d have to set the X-bit on the script to be able to run it:

# chmod u+x /root/chkip.sh

#!/bin/sh

fileip=/tmp/oldip.txt

touch $fileip
oldip=`awk '{printf$1}' $fileip`
newip=`/sbin/ifconfig ppp0|awk '{if(NR==2)printf$2"\n"}'`
if [ "$newip" != "$oldip" ]; then
 echo $newip|mail -s ip yourname@yourdomain.com
 echo $newip > $fileip
fi
Categories: Bash, Linux Tags:
  1. No comments yet.
  1. No trackbacks yet.