赞
踩
参考:
http://www.cnblogs.com/suyang/archive/2008/05/18/1201990.html
http://www.cnblogs.com/xuqiang/archive/2011/04/27/2031034.html
http://www.cnblogs.com/xudong-bupt/p/3721210.html
记录学习的笔记
1、hello world
- helloshell.sh
- #!/bin/bash
- #comments
- echo "hello world";
运行
- [root@u1 shell_learn]# sh helloshell.sh
- hello world
查看shell脚本有无语法错误
[root@u1 shell_learn]# sh -n helloshell.sh
查看展开shell脚本执行
- [root@u1 shell_learn]# sh -x helloshell.sh
- + echo 'hello world'
- hello world
打印shell读取内容
- [root@u1 shell_learn]# sh -v helloshell.sh
- #!/bin/bash
- #comments
- echo "hello world";
- hello world
- [root@u1 shell_learn]# ps
- PID TTY TIME CMD
- 39366 pts/3 00:00:00 bash
- 44076 pts/3 00:00:00 ps
2、一些细节
just for record some detail like sh -n ifshell.sh sh -v ifshell.sh sh -x ifshell.sh ``--get the command then execute ,output the result expr--mean a expression \*--translate $*--all parameter,not include the shell name $#--count the parameter number,not include the shell $0--the shell name $1--the first parameter $2 -eq -ne -lt -le -gt -ge ! -a -o = != str for-- if use ; then if no ; then
条件描述
#!/bin/sh #test condition #[ condition ] #echo $? #1--file--[ -d -f -L -r -w -x -u -s ] #2--logic--[ -a -o ! ] #3--string--[ = != -z -n ] #4--num--[ -eq -ne -gt -lt -le -ge ] #5--expr-- echo "file desc" [ -d basename.sh ] echo "$?" echo "logic desc" test -f basename.sh -a -r cat.sh echo "$?" echo "string desc" str="hello" test -n str echo "$?" echo "num desc" num=10 test $num -gt 5 echo "$?" echo "expr desc" echo "`expr 4 + 5`" echo "`expr 4 - 5`" echo "`expr 10 / 5`" echo "`expr 4 \* 5`"
结果
[u1@u1 common]$ sh -x test.sh + echo 'file desc' file desc + '[' -d basename.sh ']' + echo 1 1 + echo 'logic desc' logic desc + test -f basename.sh -a -r cat.sh + echo 0 0 + echo 'string desc' string desc + str=hello + test -n str + echo 0 0 + echo 'num desc' num desc + num=10 + test 10 -gt 5 + echo 0 0 + echo 'expr desc' expr desc ++ expr 4 + 5 + echo 9 9 ++ expr 4 - 5 + echo -1 -1 ++ expr 10 / 5 + echo 2 2 ++ expr 4 '*' 5 + echo 20 20
3、if
- [root@u1 shell_learn]# sh ifshell.sh 5
- 5 number is postive
- [root@u1 shell_learn]# sh ifshell.sh -5
- -5 number is negative
内容
#!/bin/bash #comments #$# get the input parameter , not include the command if [ $# -ne 1 ] #then must seperate if then echo "$0 : you must input a number" exit 1 fi #test like [ ] if test $1 -gt 0 then echo "$1 number is postive" else echo "$1 number is negative" fi
if -else
- [root@u1 shell_learn]# sh ifelshell.sh
- ifelshell.sh:you must a number
- [root@u1 shell_learn]# sh ifelshell.sh 5
- 5 is a positive
- [root@u1 shell_learn]# sh ifelshell.sh -5
- -5 is a negative
- [root@u1 shell_learn]# sh ifelshell.sh 0
- 0 is equal 0
- [root@u1 shell_learn]# sh ifelshell.sh a
- ifelshell.sh: line 10: [: a: integer expression expected
- ifelshell.sh: line 13: [: a: integer expression expected
- ifelshell.sh: line 16: [: a: integer expression expected
- a is not a number
内容
#!/bin/bash #comments #test if ..elif else fi if [ $# -ne 1 ] then echo "$0:you must a number" exit 1 fi #if elif else fi if [ $1 -gt 0 ] then echo "$1 is a positive" elif [ $1 -lt 0 ] then echo "$1 is a negative" elif [ $1 -eq 0 ] then echo "$1 is equal 0" else echo "$1 is not a number" fi
4、while
- [root@u1 shell_learn]# sh whileshell.sh
- whileshell.sh: must input a number
- [root@u1 shell_learn]# sh whileshell.sh 4
- 4 * 0 =0
- 4 * 1 =4
- 4 * 2 =8
- 4 * 3 =12
- 4 * 4 =16
- 4 * 5 =20
- 4 * 6 =24
- 4 * 7 =28
- 4 * 8 =32
- 4 * 9 =36
- 4 * 10 =40
内容
#!/bin/bash #comment #test while if [ $# -ne 1 ] then echo "$0: must input a number" exit 1 fi i=0 while [ $i -le 10 ] do #``--mean calculate expr and output the result echo "$1 * $i =`expr $1 \* $i`" i=`expr $i + 1` done
5、for
- [root@u1 shell_learn]# sh forshell.sh
- weleome 1 times
- weleome 2 times
- weleome 3 times
- 11111
- 22222
- 33333
- 44444
- 55555
-
- 11111
- 22222
- 33333
- 44444
- 55555
内容
#!/bin/bash #comments #test for for ii in 1 2 3 do echo "weleome $ii times" done for(( i = 1; i <= 5; i++ )) do for(( j = 1; j <= 5; ++j )) do echo -n "$i" done # print a new line echo "" done echo "" # nested for for(( i = 1; i <= 5; i++ )) do for(( j = 1; j <= 5; j++ )) do echo -n "$i" done # echo "" done
6、case
- [root@u1 shell_learn]# sh caseshell.sh
- caseshell.sh: must input a command
- [root@u1 shell_learn]# sh caseshell.sh 1
- 1 is not a valid command
- [root@u1 shell_learn]# sh caseshell.sh delete
- delete the db
- [root@u1 shell_learn]# sh caseshell.sh select
- select the db
内容
#!/bin/bash #comments # test case if [ $# -ne 1 ] then echo "$0: must input a command" exit 1 fi action=$1 case $action in "update") echo "update the db" ;; "select") echo "select the db" ;; "delete") echo "delete the db" ;; *) echo "$action is not a valid command" ;; esac
7、function and args
- [root@u1 shell_learn]# sh funcshell.sh
- shell name args:funcshell.sh
- all function args:-f foo bar
- all function agrs_num 3
- the first arg : -f
- the second arg : foo:
- shell name args:funcshell.sh
- all function args:foo bar
- all function agrs_num 2
- the first arg : foo
- the second arg : bar:
内容
#!/bin/bash #comments # test function function demo(){ echo "shell name args:$0" echo "all function args:$*" echo "all function agrs_num $#" echo "the first arg : $1" echo "the second arg : $2:" shift echo "shell name args:$0" echo "all function args:$*" echo "all function agrs_num $#" echo "the first arg : $1" echo "the second arg : $2:" } #call the function demo -f foo bar
8、date
- [root@u1 shell_learn]# sh cmd_learn/date.sh
- [root@u1 shell_learn]# cat cmd_learn/date.log
- 2015-07-22 11:44:21
内容
- #!/bin/bash
- #
- echo "`date -d today +"%Y-%m-%d %T"`" > /home/u1/shell_learn/cmd_learn/date.log
9、find
- [root@u1 shell_learn]# sh cmd_learn/find.sh
- [root@u1 shell_learn]# tail -f cmd_learn/find.log
- /opt/ibm/db2/V10.5/license/sl_SI.iso88592
- /opt/ibm/db2/V10.5/license/el_GR.iso88597
- /opt/ibm/db2/V10.5/license/lt_LT.iso885913
- /opt/ibm/db2/V10.5/license/pl_PL.iso88592
- /opt/ibm/db2/V10.5/license/cs_CZ.iso88592
- /opt/ibm/db2/V10.5/license/fr_FR.iso88591
- /opt/ibm/db2/V10.5/license/de_DE.iso88591
- /opt/ibm/db2/V10.5/license/es_ES.iso88591
- /opt/ibm/db2/V10.5/license/pt_BR.iso88591
- /opt/ibm/db2/V10.5/license/en_US.iso88591
内容
- #!/bin/bash
- #comments
-
- find / -name "[a-z]*[0-9][0-9]" -print > find.log 2>&1
- #find ./ -name "*.sh" -print > find.log 2>&1
-
10、in_out
[root@u1 shell_learn]# sh cmd_learn/in_out.sh display display display display : first name : qq second name :ali qq ali u1 tty1 2015-07-16 22:00 u1 pts/0 2015-07-17 00:34 (:0.0) root pts/3 2015-07-22 10:32 (192.168.147.1) [root@u1 shell_learn]# cat wh whileshell.sh who.out [root@u1 shell_learn]# cat who.out u1 tty1 2015-07-16 22:00 u1 pts/0 2015-07-17 00:34 (:0.0) root pts/3 2015-07-22 10:32 (192.168.147.1) [root@u1 shell_learn]# cat in_out.log 2015-07-22 11:57:59 1
内容
#!/bin/bash #echo cat read tee | #in--0 < << #out--1 > >> #err--2 2>&1 #echo echo "display" echo -e "display \n" echo -n -e "display \t" echo -e "display :\c" echo "" #read echo -e "first name : \c" read name echo -e "second name :\c" read middle echo "$name $middle" #cat #cat -v > cat_read.log #tee who | tee who.out #0 1 2 echo "`date -d today +"%Y-%m-%d %T"`" 1 >> in_out.log 2>&1
11、read
- [root@u1 shell_learn]# sh readshell.sh
- 1.unix(sun os)
- 2.linux(redhat)
- select your os choice [1 or 2] ?2
- you pick up linux
- [root@u1 shell_learn]# sh readshell.sh
- 1.unix(sun os)
- 2.linux(redhat)
- select your os choice [1 or 2] ?4
- what you donot like linux/unix
内容
#!/bin/sh #comments #define a variable osch=0 #display prompt echo "1.unix(sun os)" echo "2.linux(redhat)" echo -n "select your os choice [1 or 2] ?" #wait user input read osch #if if [ $osch -eq 1 ] then echo "you pick up unix" else #nested if if [ $osch -eq 2 ] then echo "you pick up linux" else echo "what you donot like linux/unix" fi fi
12、rename file
[root@u1 shell_learn]# ls back_syncDeptFtp.sh forshell.sh ifshell.sh syncDeptFtp.sh caseshell.sh funcshell.sh in_out.log whileshell.sh cmd_learn getFtpFile.sh multisyncDeptFtp.sh who.out data getSyncStatus.sh readme.txt debugshell.sh helloshell.sh readshell.sh find.log ifelshell.sh rename.sh [root@u1 shell_learn]# sh rename.sh rename--renames a number of files using sed regular repressions USAGE: rename 'regexp' 'relpacement' files EXAMPLE:rename all *.HTM files in *.html rename 'sh$' 'SH' *.sh [root@u1 shell_learn]# sh rename.sh sh$ SH *.sh renaming back_syncDeptFtp.sh to back_syncDeptFtp.SH renaming caseshell.sh to caseshell.SH renaming debugshell.sh to debugshell.SH renaming forshell.sh to forshell.SH renaming funcshell.sh to funcshell.SH renaming getFtpFile.sh to getFtpFile.SH renaming getSyncStatus.sh to getSyncStatus.SH renaming helloshell.sh to helloshell.SH renaming ifelshell.sh to ifelshell.SH renaming ifshell.sh to ifshell.SH renaming multisyncDeptFtp.sh to multisyncDeptFtp.SH renaming readshell.sh to readshell.SH renaming rename.sh to rename.SH renaming syncDeptFtp.sh to syncDeptFtp.SH renaming whileshell.sh to whileshell.SH [root@u1 shell_learn]# ls back_syncDeptFtp.SH forshell.SH ifshell.SH syncDeptFtp.SH caseshell.SH funcshell.SH in_out.log whileshell.SH cmd_learn getFtpFile.SH multisyncDeptFtp.SH who.out data getSyncStatus.SH readme.txt debugshell.SH helloshell.SH readshell.SH find.log ifelshell.SH rename.SH
内容
- #!/bin/bash
- #comments
- # test rename file
- if [ $# -lt 3 ]
- then
- cat<<HELP
- rename--renames a number of files using sed regular repressions
- USAGE: rename 'regexp' 'relpacement' files
- EXAMPLE:rename all *.HTM files in *.html
- rename 'sh$' 'SH' *.sh
- HELP
- exit 0
- fi
- #
- old=$1
- new=$2
- shift
- shift
- for file in $*
- do
- if [ -f $file ]; then
- newfile=`echo $file | sed "s/${old}/${new}/g"`
- if [ -f $newfile ] ;then
- echo "error:$newfile exists already"
- else
- echo "renaming $file to $newfile"
- mv $file $newfile
- fi
- fi
- done
-
13、debug info
[root@u1 shell_learn]# sh -v debugshell.sh #!/bin/bash #comments # test debug tot=`expr $1 + $2` expr $1 + $2 expr: 语法错误 echo $tot [root@u1 shell_learn]# sh -v debugshell.sh 4 5 #!/bin/bash #comments # test debug tot=`expr $1 + $2` expr $1 + $2 echo $tot 9
内容
- #!/bin/bash
- #comments
- # test debug
- tot=`expr $1 + $2`
- echo $tot
14、crontab & nohup
- #!/bin/bash
- #cron crontab at & nohup
- #crontab [-u user] -e -l -r
- #crontab <filename>
- #example
- #0-59 0-23 1-31 1-12 0-6
- #minute hour day month week shell_name
- #1-3 1,3 *
- #in shell_name ,the path use absolute path,not relative path
-
crontab--需要注意,提交到crontab中的脚本,需要使用绝对路径,因为crontab调度程序是不识别用户的环境变量的
eg:
每分钟都执行date.sh脚本
* * * * * /home/u1/shell_learn/cmd_learn/date.sh
&--后台进程运行
nohup--无需守护,也可运行
15、再附上几个觉得在部署系统时,常用的几个命令
查找端口、进程
- [root@u1 shell_learn]# netstat -aonp | grep 8080
- tcp 0 0 :::8080 :::* LISTEN 60571/java off (0.00/0/0)
- [root@u1 shell_learn]# ps -ef | grep ps
- root 41 2 0 Jul16 ? 00:00:00 [kpsmoused]
- root 1615 1 0 Jul16 ? 00:00:00 cupsd -C /etc/cups/cupsd.conf
- root 49227 39366 3 12:12 pts/3 00:00:00 ps -ef
- root 49228 39366 0 12:12 pts/3 00:00:00 grep ps
-
- 关闭进程
- kill -9 49228
最近在做一个项目 需要在shell中 进行数据库的同步、数据库的备份等功能,发现shell的功能,不得不要为他点赞,太强大了,以上为shell的基本内容,继续研究。。。
16、 常用命令
- #!/bin/sh
- #basename cat cp diff dircmp
- #dirname du file fuser head
- #logname mkdir more nl printf
- #pwd rm rmdir shutdown sleep
- #strings touch tty uname wc
- #wait whereis who whoami
- [u1@u1 common]$ cat script.sh
- #!/bin/sh
- #basename cat cp diff dircmp
- #dirname du file fuser head
- #logname mkdir more nl printf
- #pwd rm rmdir shutdown sleep
- #strings touch tty uname wc
- #wait whereis who whoami script
basename
- [u1@u1 common]$ cat basename.sh
- #!/bin/sh
- #basename path
- #get file name from path
- echo "uasge:`basename $0` file"
- exit 1
- [u1@u1 common]$ sh /home/u1/mtsd3/shell_learn/common/basename.sh
- uasge:basename.sh file
tar
- [u1@u1 common]$ cat tar.sh
- #!/bin/sh
- #tar options files
- cp cat.sh cat1.sh
- ls
- tar -zcvf cat.tar.gz cat1.sh
- rm -f cat1.sh
- ls
- tar -zxvf cat.tar.gz
- ls
more
- [u1@u1 common]$ cat more.sh
- #!/bin/sh
- #more filename
- #space-next b--previous
- more ../../gateway3.1_mq/centrumserver/centrumserver.sh
nl
- [u1@u1 common]$ cat nl.sh
- #!/bin/sh
- #nl filename
- nl basename.sh
awk
- #!/bin/sh
- #as line deal
- #awk -F":" '{if($1~/u1/)print $1}' /etc/passwd
- #awk '{print NF}' basename.sh
- #awk '{print $1,$2}' OFS='\t' basename.sh
- awk 'BEGIN{math=0;eng=0;com=0;printf "Lineno. Name No. Math English Computer Total\n";printf "------------------------------------------------------------\n"}{math+=$3; eng+=$4; com+=$5;printf "%-8s %-7s %-7s %-7s %-9s %-10s %-7s \n",NR,$1,$2,$3,$4,$5,$3+$4+$5} END{printf "------------------------------------------------------------\n";printf "%-24s %-7s %-9s %-20s \n","Total:",math,eng,com;printf "%-24s %-7s %-9s %-20s \n","Avg:",math/NR,eng/NR,com/NR}' test0
- [root@u1 common]# cat test0
- Marry 2143 78 84 77
- Jack 2321 66 78 45
- Tom 2122 48 77 71
- Mike 2537 87 97 95
- Bob 2415 40 57 62
- [root@u1 common]# sh awk.sh
- Lineno. Name No. Math English Computer Total
- ------------------------------------------------------------
- 1 Marry 2143 78 84 77 239
- 2 Jack 2321 66 78 45 189
- 3 Tom 2122 48 77 71 196
- 4 Mike 2537 87 97 95 279
- 5 Bob 2415 40 57 62 159
- ------------------------------------------------------------
- Total: 319 393 350
- Avg: 63.8 78.6 70
grep sed cut awk 组合实例:
- #!/bin/sh
- #grep n--lien number
- # i--ignore case
- # want_search_text file
- #cut -d delimiter -f field 1 2
- #awk -v variable ' $1 $2'
- #sed s separator $want_text$replace_text$g
- #especially want value to variable, use ``
- fl=`grep -ni dead alertDeadLock.log | cut -d: -f 2 | awk -v 'OFS=*' '{print $1,$2,$3 }' | sed 's$*$-$g'`
-
-
- echo $fl
alertDeadLock.log文本内容
- ######################## 2015-12-22 18:28:24 ########################
- LATEST DETECTED DEADLOCK
- ------------------------
- 151222 18:10:54
- *** (1) TRANSACTION:
- TRANSACTION 7A7BE4, ACTIVE 324 sec starting index read
- mysql tables in use 1, locked 1
- LOCK WAIT 4 lock struct(s), heap size 1248, 3 row lock(s)
- MySQL thread id 8574, query id 6854603 172.16.22.243 root statistics
- select a,b,c from dltask where a='a8063001' and b='b99088948' and c='c71255728' for update
- *** (1) WAITING FOR THIS LOCK TO BE GRANTED:
- RECORD LOCKS space id 0 page no 1414168 n bits 336 index `uniq_a_b_c` of table `400_5.1_gsms`.`dltask` trx id 7A7BE4 lock_mode X locks rec but not gap waiting
- Record lock, heap no 171 PHYSICAL RECORD: n_fields 4; compact format; info bits 0
- 0: len 8; hex 6138303633303031; asc a8063001;;
- 1: len 9; hex 623939303838393438; asc b99088948;;
- 2: len 9; hex 633731323535373238; asc c71255728;;
- 3: len 8; hex 0000000000000002; asc ;;
-
- *** (2) TRANSACTION:
- TRANSACTION 7A7BE5, ACTIVE 316 sec starting index read
- mysql tables in use 1, locked 1
- 4 lock struct(s), heap size 1248, 3 row lock(s)
- MySQL thread id 8575, query id 6854605 172.16.22.243 root statistics
- select a,b,c from dltask where a='a77584148' and b='b55038073' and c='c42437915' for update
- *** (2) HOLDS THE LOCK(S):
- RECORD LOCKS space id 0 page no 1414168 n bits 336 index `uniq_a_b_c` of table `400_5.1_gsms`.`dltask` trx id 7A7BE5 lock_mode X locks rec but not gap
- Record lock, heap no 171 PHYSICAL RECORD: n_fields 4; compact format; info bits 0
- 0: len 8; hex 6138303633303031; asc a8063001;;
- 1: len 9; hex 623939303838393438; asc b99088948;;
- 2: len 9; hex 633731323535373238; asc c71255728;;
- 3: len 8; hex 0000000000000002; asc ;;
-
- *** (2) WAITING FOR THIS LOCK TO BE GRANTED:
- RECORD LOCKS space id 0 page no 1347520 n bits 432 index `uniq_a_b_c` of table `400_5.1_gsms`.`dltask` trx id 7A7BE5 lock_mode X locks rec but not gap waiting
- Record lock, heap no 190 PHYSICAL RECORD: n_fields 4; compact format; info bits 0
- 0: len 9; hex 613737353834313438; asc a77584148;;
- 1: len 9; hex 623535303338303733; asc b55038073;;
- 2: len 9; hex 633432343337393135; asc c42437915;;
- 3: len 8; hex 0000000000000001; asc ;;
-
- *** WE ROLL BACK TRANSACTION (2)
[root@u1 deadlock]# sh grep_cut_sed_awk.sh
LATEST-DETECTED-DEADLOCK
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。