상세 컨텐츠

본문 제목

Bash 소스

개발

by 동동주1123 2012. 4. 8. 20:13

본문

# File Desciption : IBM Dev article source code for "Bash Scripting for Beginning System Admins"

# Script Version : 2.1

# Date :   09/14/2010

# Author : roger.hill

# Desc :   IBM Dev article source code for "Bash Scripting for Beginning System Admins"


-------------------------------------------------

# Listing 1 - Bash Profile 


[fred.smythe@server01 ~]$ cat .bash_profile

# .bash_profile


# Get the aliases and functions

if [ -f ~/.bashrc ]; then

        . ~/.bashrc

fi


# User specific environment and startup programs

export JAVA_HOME=/usr/java/default

export PATH=$JAVA_HOME/bin:$PATH


PATH=$PATH:$HOME/bin


export PATH


-------------------------------------------------

# Listing 2 - Bash RC file 


# .bashrc


# User specific aliases and functions


alias rm='rm -i'

alias cp='cp -i'

alias mv='mv -i'

alias tc6='cd /opt/tomcat/6.0.13'

alias conf6='cd /opt/tomcat/6.0.13/conf'

alias bin6='cd /opt/tomcat/6.0.13/bin'

alias scr='cd /opt/tomcat/scripts'

alias reports='cd /opt/tomcat/reports'

alias temp6='cd /opt/tomcat/6.0.13/template'


# Source global definitions

if [ -f /etc/bashrc ]; then

        . /etc/bashrc

fi



-------------------------------------------------

# Listing 4 - fullpath 

[fred.smythe@server01 ~]$ /sbin/ifconfig -a

eth0      Link encap:Ethernet  HWaddr 00:50:56:96:2E:B3

          inet addr:10.14.33.60  Bcast:10.14.33.255  Mask:255.255.255.0


-------------------------------------------------

# Listing 5 - Set an Alias 


[fred.smythe@server01 ~]$ alias ifconfig='/sbin/ifconfig'

[fred.smythe@server01 ~]$ ifconfig

eth0      Link encap:Ethernet  HWaddr 00:50:56:96:2E:B3

          inet addr:10.14.33.60  Bcast:10.14.33.255  Mask:255.255.255.0

          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1

-------------------------------------------------

# Listing 6 - Exit code example 

# ls -ld /tmp

drwxrwxrwt 5 root root 4096 Aug 19 19:45 /tmp

[root@server01 ~]# echo $?

0 // Good command return of 0.

[root@server01 ~]# ls -l /junk

ls: /junk: No such file or directory

[root@server01 ~]# echo $?

2 // Something went wrong, there was an error, so return 2.


-------------------------------------------------

# Listing 7 - Child and Parent process (parent pid = 8495, child pid = 9254)

[root@server02 htdocs]# ps -ef | grep httpd

UID       PID   PPID  C STIME TTY      TIME      CMD

root      8495     1  0 Jul26 ?        00:00:03 /usr/sbin/httpd -k start 

apache    9254  8495  0 Aug15 ?        00:00:00 /usr/sbin/httpd -k start 


-------------------------------------------------

# Listing 8 - Bash environment 

[fred.smythe@server01 ~]$ env

HOSTNAME=server01

TERM=screen

SHELL=/bin/bash

HISTSIZE=1000

SSH_CLIENT=10.12.132.3 56513 22

SSH_TTY=/dev/pts/0

USER=fred.smythe

LS_COLORS=no=00:fi=00:di=01;34:ln=01;36:pi=40;33:so=01;35:bd=40;33;01:cd=40;33;01:or=01;05

;37;41:mi=01;05;37;41:ex=01;32:*.cmd=01;32:*.exe=01;32:*.com=01;32:*.btm=01;32:*.bat=01;32

:*.sh=01;32:*.csh=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.zip=

01;31:*.z=01;31:*.Z=01;31:*.gz=01;31:*.bz2=01;31:*.bz=01;31:*.tz=01;31:*.rpm=01;31:*.cpio=

01;31:*.jpg=01;35:*.gif=01;35:*.bmp=01;35:*.xbm=01;35:*.xpm=01;35:*.png=01;35:*.tif=01;35:

MAIL=/var/spool/mail/fred.smythe

PATH=/usr/local/bin:/bin:/usr/bin:/home/fred.smythe/bin

INPUTRC=/etc/inputrc

PWD=/home/fred.smythe

LANG=en_US.UTF-8

SHLVL=1

HOME=/home/fred.smythe

LOGNAME=fred.smythe

SSH_CONNECTION=10.14.43.183 56513 10.14.43.43 22

LESSOPEN=|/usr/bin/lesspipe.sh %s

G_BROKEN_FILENAMES=1

_=/bin/env



-------------------------------------------------

# Listing 9 - Navigating in basah 

[fred.smythe@server01 ~]$ ls -l

total 0

[fred.smythe@server01 ~]$ cd /tmp

[fred.smythe@server01 tmp]$ df -ha .

Filesystem            Size  Used Avail Use% Mounted on

/dev/mapper/vg_root-lv_tmp

                      2.0G   68M  1.8G   4% /tmp


-------------------------------------------------

# Listing 10 - Sequential Command execution in bash 

fred.smythe@server01 tmp]$ ls -l ;cd /tmp;df -ha .

total 40

-rw-r----- 1 root root  1748 May 22  2009 index.html

-rw-r----- 1 root root   786 Aug 17 04:59 index.jsp

drwx------ 2 root root 16384 Jul 15  2009 lost+found

drwx------ 2 root root  4096 Aug  9 21:04 vmware-root

Filesystem            Size  Used Avail Use% Mounted on

/dev/mapper/vg_root-lv_tmp

                      2.0G   68M  1.8G   4% /tmp

[fred.smythe@server01 tmp]$


-------------------------------------------------

# Listing 17 - type command 

[root@apache-02 htdocs]# type lsof

lsof is /usr/sbin/lsof

[root@apache-02 htdocs]# type alias

alias is a shell builtin


-------------------------------------------------

# Listing 18 - Which command in bash 

[root@server01 ~]# which lsof

/usr/sbin/lsof

[root@server01 ~]# rpm -qa lsof-4.78-3.i386

[root@server01 ~]# rpm -qa lsof

lsof-4.78-3.i386


-------------------------------------------------

# Listing 19 - Scripting on the fly in bash 

[fred.smythe@server01 ~]$ DEBUG=1

[fred.smythe@server01 ~]$ test $DEBUG -gt 0 && echo "Debug turned on"

Debug turned on


-------------------------------------------------

# Listing 20 - Scripting a 'for loop' 'on the fly' in bash 

$ for SVR in 1 2 3

> do

> echo server0$SVR.example.com

> done

server01.example.com

server02.example.com

server03.example.com


-------------------------------------------------

# Listing 21 - A for loop on a single command line 

$ for SVR in 1 2 3; do  echo server0$SVR.example.com; done

server01.example.com

server02.example.com

server03.example.com


-------------------------------------------------

# Listing 23 - Piping command together in bash 

$ USER="fred.smythe"

$ echo -n "User $USER home is: " && cat /etc/passwd | grep $USER | awk -F: '{print $6}'

User fred.smythe home is: /home/fred.smythe

$

# Re-direction of standard output (>) of the date command to a file : 

[root@server01 ~]# date > /tmp/today.txt

[root@server01 ~]# cat /tmp/today.txt

Thu Aug 19 19:38:33 UTC 2010 


# Re-direction of standard input (<) to standard output (>) ?

[root@server01 ~]# cat < /tmp/today.txt > /tmp/today.txt.backup

[root@server01 ~]# cat /tmp/today.txt.backup

Thu Aug 19 19:38:33 UTC 2010


-------------------------------------------------

# Listing 24 - Re-direction example 

# command1 < input_file1.txt > output_file1.txt

# command1 | command2 | command3 > output_file.log


-------------------------------------------------

# Listing 25 - Using a complex command line with 'find' 

$ find ./ -name 'error_log.*.gz' | xargs zcat | grep 'Permission denied'| wc -l

3


-------------------------------------------------

# Listing 26 - Plain bash script example 

#!/bin/bash


cd /data01/maillog


MAILSVRS=$(/bin/cat /data01/maillog/mail_servers)

DATELOG=`date "+%m%d%y"`

ALLMAILLOGS="/data01/maillog/all_svr_maillogs.$DATELOG"

MAILREPORT="/data01/maillog/all_svr_maillogs.report.$DATELOG"

MAILADDRESSES=$(/bin/cat /data01/maillog/addresses)

MAILADMINS="admin1@example.com, admin2@example.com"

MAILSTATSLOGALL="/data01/maillog/mailstats.log.all.$DATELOG"

DELDAYSLOGS=10


echo "Mail Report to $ MAILADMINS"


# 1 - Get some logs ...

for svr in $MAILSVRS

do

  if [ -e "/data01/maillog/$svr.maillog.$DATELOG.gz" ]; then

     /bin/rm -f /data01/maillog/$svr.maillog.$DATELOG.gz

  fi

done


# 2 - Combine all maillogs from all servers to onefile ($ALLMAILLOGS) ...

/bin/zcat server16.maillog.$DATELOG.gz server17.maillog.$DATELOG.gz 

server18.maillog.$DATELOG.gz server19.maillog.$DATELOG.gz >> 

$ALLMAILLOGS


# 3 - Run another script 

/bin/cat $ALLMAILLOGS | /data01/maillog/mymailstats.pl | tee -a $MAILREPORT


# 4 -  Get all of the mailstats logs to one log file to send by Email

  /bin/cat /data01/maillog/mailstats.log.server*.$DATELOG > $MAILSTATSLOGALL

# Send the $MAILADMINS the mail reports

  /bin/cat $MAILSTATSLOGALL | mail -s "ACME Servers Outbound Mail Servers 

  mailstats:$DATELOG" $MAILADMINS


-------------------------------------------------

# Listing 27 - Improved Example of Bash Script 

#!/bin/bash


# Script Desciption : mail_stats_wrapper.sh

# Script Version : 2.1

# Date :   03/27/2009

# Author : fred.smith

# Operating System : RHEL 5.5 32 bit

# Desc :   To gather all of last days mail logs from servers 16, 17, 18, 19 ...


# Added for crontab PWD ...

cd /data01/maillog


MAILSVRS=$(/bin/cat /data01/maillog/mail_servers)

DATEFMT=`date "+%m/%d/%Y %H:%M:%S"`

DATELOG=`date "+%m%d%y"`

LOGFILE="/data01/maillog/mail_stats_wrapper.log.$DATELOG"

ALLMAILLOGS="/data01/maillog/all_svr_maillogs.$DATELOG"

MAILREPORT="/data01/maillog/all_svr_maillogs.report.$DATELOG"

MAILADDRESSES=$(/bin/cat /data01/maillog/addresses)

MAILADMINS="admin1@example.com, admin2@example.com"

MAILSTATSLOGALL="/data01/maillog/mailstats.log.all.$DATELOG"

DELDAYSLOGS=10


logit() {

  # a simple logging function

  DATEFMT=`date "+%m/%d/%Y %H:%M:%S"`

  echo "$DATEFMT: $1" | tee -a $LOGFILE

}


logit "******************************************************************************"

logit "/data01/maillog/mail_stats_wrapper.sh is STARTING ..."

logit "******************************************************************************"


logit "Date : $DATEFMT"

logit "Logfile : $LOGFILE"

logit "All Mail Logs : $ALLMAILLOGS"

logit "Mail Report : $MAILREPORT"


logit "List of Mail Admin Recepients : $MAILADMINS"

logit "---------------------------------------------------------------"


# 1.0 scp yesterday's compressed maillog file from each server to this server ...

for svr in $MAILSVRS

do

  if [ -e "/data01/maillog/$svr.maillog.$DATELOG.gz" ]; then

    logit "Removing older previous file $svr.maillog.$DATELOG.gz ..."

    /bin/rm -f /data01/maillog/$svr.maillog.$DATELOG.gz

  fi

  logit "Retreving Yesterdays mail log from : $svr.example.com ..."

  /usr/bin/scp $svr.example.com:/data01/maillog/maillog.1.gz $svr.maillog.$DATELOG.gz | 

  tee -a $LOGFILE

done


# 2.0 Remove the old combined maillog file ($ALLMAILLOGS) ...

if [ -e "$ALLMAILLOGS" -o -e "$ALLMAILLOGS.gz" ];then

  logit "Removing older logs $ALLMAILLOGS and $ALLMAILLOGS.gz files if the exist ..."

  /bin/rm -f $ALLMAILLOGS $ALLMAILLOGS.gz

fi


# 2.1 Combine all maillogs from all servers to onefile ($ALLMAILLOGS) ...

logit "Combining all mail server logs into one log ($ALLMAILLOGS) file ..."

/bin/zcat server16.maillog.$DATELOG.gz server17.maillog.$DATELOG.gz 

server18.maillog.$DATELOG.gz server19.maillog.$DATELOG.gz >> 

$ALLMAILLOGS


# 3.0 Remove the old mail report file ($MAILREPORT) ...

if [ -e "$MAILREPORT" ];then

  logit "Removing older previous $MAILREPORT log file ..."

  /bin/rm -f $MAILREPORT

fi


# 3.1 Run another script, the mymailstats.pl script with the combined maillog file 

# for all traffic yesterday ...

logit "Running mymailstats.pl with parameter $ALLMAILLOGS output report is $MAILREPORT"

/bin/cat $ALLMAILLOGS | /data01/maillog/mymailstats.pl | tee -a $MAILREPORT


# 4.1 gzip todays log $ALLMAILLOGS to save space (since we've already run the report)....

logit "Compressing log : $ALLMAILLOGS"

gzip --best $ALLMAILLOGS


# 4.2 Rotate your own logs , and maillog source logs , and the combined log file ...

logit "Checking and my own old logs and maillogs to rotate from $DELDAYSLOGS ago..."

LOGS2REMOVE=$(find /data01/maillog -name "*log*" -mtime $DELDAYSLOGS)

for log in $LOGS2REMOVE

do

  logit "Removing $log"

  /bin/rm -f $log

done


# 5.0 Cross reference with the mailstats command output ... (if possbile) ...

for svr in $MAILSVRS

do

  logit "Retreving mailstats from : $svr.example.com ..."

  echo "MAILSTATS REPORT : $svr.example.com" > /data01/maillog/mailstats.log.$svr.$DATELOG

  /usr/bin/ssh $svr.example.com mailstats | tee -a 

  /data01/maillog/mailstats.log.$svr.$DATELOG

  echo " " >> /data01/maillog/mailstats.log.$svr.$DATELOG

done


# 6.0 Get all of the mailstats logs to one log file to send by Email

  /bin/cat /data01/maillog/mailstats.log.server*.$DATELOG > $MAILSTATSLOGALL

# Send the $MAILADMINS the mail reports

  /bin/cat $MAILSTATSLOGALL | mail -s "ACME Servers Outbound Mail Servers 

  mailstats:$DATELOG" $MAILADMINS


logit "******************************************************************************"

logit "/data01/maillog/mail_stats_wrapper.sh is ENDING ..."

logit "******************************************************************************"

logit " "


exit 0


-------------------------------------------------

# Listing 28 - Define bash variables 

$ cat a.sh

#!/bin/bash


A="String Value 1"

B='String Value 2'

C=9675

D=96.75

export E="String Value 3"

# if the variable $F is not ALREADY set to a value, assign "String Value 4" ...

F=${F:="String Value 4"}


echo "A=$A"

echo "B=$B"

echo "C=$C"

echo "D=$D"

echo "E=$E"

echo "F=$F"


exit 0


-------------------------------------------------

# Listing 31 - Working with passed parameters in bash 

cat param.sh

#!/bin/bash

PARAM1=$1

PARAM2=$2

PARAM3=$3

echo "You have passed to me Parameter 1 == $PARAM1, Parameter 2 == $PARAM2, Parameter 

3 == $PARAM3"

exit 0


-------------------------------------------------

# Listing 32 - User input in bahs 

$ cat prompt.sh

#!/bin/bash

echo "Please enter your first and last name:"

read ans

echo "Hellow $ans , welcome to bash scripting ...!"

exit 0


$ ./prompt.sh

Please enter your first and last name:

Joe Jackson

Hello Joe Jackson , welcome to bash scripting ...!


-------------------------------------------------

# Listing 33- Assignment Operators in bash 

# Comment 

= Assignment Operator or if used with if or test equality test

== Equality Test operator

!= Not Equal to (string compare)

< Less than (string compare)

> Greater than (string compare)

-z zero length string (string compare)

-n string is not null (string compare)

-eq is equal to (integer comparison)

-ne is not equal to (integer comparison)

-ge is greater than or equal to (integer comparison)

-gt is greater than (integer comparison)

-lt is less than (integer comparison)

-le is less than or equal to (integer comparison)


-------------------------------------------------

# Listing 34 - Mathematical Operators in bash 

+ plus

- minus

* multiplication

/ division

** exponentiation

% modulo, or mod (returns the remainder of an integer division operation)

+= plus-equal (increment variable by a constant)

            let "num += 1" results in num being incremented by 1.

          

-= minus-equal (decrement variable by a constant)

*= times-equal (multiply variable by a constant)

            let "num *= 2" results in num being multiplied by 2.

          

/= slash-equal (divide variable by a constant)

%= mod-equal (remainder of dividing variable by a constant)




-------------------------------------------------

# Listing 35 - Bitwise Operators in bash 

The bitwise operator are valid in bash, below is a brief definition :


<< bitwise left shift (multiplies by 2 for each shift position)

<<= left-shift-equal

              let "var < < = 2" results in var left-shifted 2 bits (multiplied by 4)

>> bitwise right shift (divides by 2 for each shift position)

>>= right-shift-equal (inverse of <<=)

& bitwise AND

&= bitwise AND-equal

| bitwise OR

|= bitwise OR-equal

~ bitwise NOT

^ bitwise XOR

^= bitwise XOR-equal

Here are bash logical (boolean) operators, there is only a few :


! NOT

&& AND

|| OR



-------------------------------------------------

# Listing 36 - Functions within bahs 

$ cat function.sh

#!/bin/bash


funcOne() {

  echo "Running function 1, with parameter $1"

  date

  echo "Current listing /tmp directory, last 3 lines"

  ls -lrt /tmp | tail -3

}


echo "Hello World"

funcOne "Server01"

exit 0


$ ./function.sh

Hello World

Running function 1, with parameter Server01

Sun Aug 22 22:43:04 UTC 2010

Current listing /tmp directory, last 3 lines

-rw-r-----  1 dsmith   progdevel 12749743 Aug 16 20:32 files.tar.gz

drwxr-xr-x  2 jjones   progdevel     4096 Aug 16 20:42 ff_hosting_files

-rw-r-----  1 rhill    heng          1440 Aug 22 19:07 myscript.log


-------------------------------------------------

# Listing 37 - Alternate functions within bash 

#!/bin/bash


function funcTwo () {

  echo "Running function 2, with parameter $1"

  date

  echo "Current listing /var directory, last 3 lines"

  ls -lrt /var | tail -3

}


funcTwo "Server02"


exit 0


$ ./function.sh

Running function 2, with parameter Server02

Sun Aug 22 22:53:16 UTC 2010

Current listing /var directory, last 3 lines

drwxrwxrwt   3 root    root     4096 Aug  6 18:22 tmp

drwxr-xr-x   6 root    root     4096 Aug 22 04:02 log

drwxrwxr-x   4 root    lock     4096 Aug 22 04:22 lock


-------------------------------------------------

# Listing 38 - For loop used with a list in bash 

$SERVERS="server01 server02 server03 server04 server05"

for i in $SERVERS

do

  echo "Removing file from server: $i"

  ssh $i rm -f /tmp/junk1.txt 

done


-------------------------------------------------

# Listing 39 - While loop example with a counter 

LOOPCTR=1

while [ $LOOPCTR -lt 6 ]

do

  echo "Running patch script for server0$LOOPCTR"

  /data/patch.sh server0$LOOPCTR

  LOOPCTR=`expr $LOOPCTR + 1`

done 


-------------------------------------------------

# Listing 40 - Case statement example in bash 

  case $key in

  q) logit "Quit";

     exit;;

  1) echo "\tChecking Mail Servers";

     check_mail_servers;;

  2) echo "\tChecking Web Servers";

     check_web_servers;;

  3) echo "\tChecking App Servers;

     check_app_servers;;

  4) echo "\tChecking Database Servers";

     check_database_servers;;

  b) echo  "Go Back to Main menu";

     MENUFLAG="main";

     main_menu;;

  *) echo "$key invalid choice";

     invalid;;

  esac





'개발' 카테고리의 다른 글

5 tips for proper Java Heap size  (0) 2012.07.19
ANT 참고 내용  (0) 2012.02.23
오라클 클라이언트 10g x64 설치시 운영체제 오류  (0) 2012.02.09

관련글 더보기