linux shell学习

来源:互联网 发布:网络小贷业务模式 编辑:程序博客网 时间:2024/06/14 13:11

参考:

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#commentsecho "hello world";

运行

[root@u1 shell_learn]# sh helloshell.shhello 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#commentsecho "hello world";hello world


查看当前执行shell 版本

[root@u1 shell_learn]# ps  PID TTY          TIME CMD39366 pts/3    00:00:00 bash44076 pts/3    00:00:00 ps


 2、一些细节

just for record some detaillikesh -n ifshell.shsh -v ifshell.shsh -x ifshell.sh``--get the command then execute ,output the resultexpr--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= != strfor-- if use ; thenif 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.shecho "$?"echo "string desc"str="hello"test -n strecho "$?"echo "num desc"num=10test $num -gt 5echo "$?"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 11+ echo 'logic desc'logic desc+ test -f basename.sh -a -r cat.sh+ echo 00+ echo 'string desc'string desc+ str=hello+ test -n str+ echo 00+ echo 'num desc'num desc+ num=10+ test 10 -gt 5+ echo 00+ echo 'expr desc'expr desc++ expr 4 + 5+ echo 99++ expr 4 - 5+ echo -1-1++ expr 10 / 5+ echo 22++ expr 4 '*' 5+ echo 2020




3、if

[root@u1 shell_learn]# sh ifshell.sh 55 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 commandif [ $# -ne 1 ]#then must seperate ifthenecho "$0 : you must input a number"exit 1fi#test like [ ] if test $1 -gt 0 thenecho "$1 number is postive"elseecho "$1 number is negative"fi


 if -else

[root@u1 shell_learn]# sh ifelshell.shifelshell.sh:you must a number[root@u1 shell_learn]# sh ifelshell.sh 55 is a positive[root@u1 shell_learn]# sh ifelshell.sh -5-5 is a negative[root@u1 shell_learn]# sh ifelshell.sh 00 is equal 0[root@u1 shell_learn]# sh ifelshell.sh aifelshell.sh: line 10: [: a: integer expression expectedifelshell.sh: line 13: [: a: integer expression expectedifelshell.sh: line 16: [: a: integer expression expecteda is not a number


内容

#!/bin/bash#comments#test if ..elif  else  fiif [ $# -ne 1 ]thenecho "$0:you must a number"exit 1fi#if elif else fiif [ $1 -gt 0 ]thenecho "$1 is a positive"elif [ $1 -lt 0 ]thenecho "$1 is a negative"elif [ $1 -eq 0 ]thenecho "$1 is equal 0"elseecho "$1 is not a number"fi



4、while

[root@u1 shell_learn]# sh whileshell.shwhileshell.sh: must input a number[root@u1 shell_learn]# sh whileshell.sh 44 * 0 =04 * 1 =44 * 2 =84 * 3 =124 * 4 =164 * 5 =204 * 6 =244 * 7 =284 * 8 =324 * 9 =364 * 10 =40


内容

#!/bin/bash#comment#test whileif [ $# -ne 1 ]thenecho "$0: must input a number"exit 1fii=0while [ $i -le 10 ]do#``--mean calculate expr and output the resultecho "$1 * $i =`expr $1 \* $i`"i=`expr $i + 1`done



5、for

[root@u1 shell_learn]# sh forshell.shweleome 1 timesweleome 2 timesweleome 3 times11111222223333344444555551111122222333334444455555

内容

 

#!/bin/bash#comments#test forfor ii in 1 2 3doecho "weleome $ii times"donefor(( i = 1; i <= 5; i++  ))do         for(( j = 1; j <= 5; ++j ))         do                 echo -n "$i"         done# print a new line         echo "" doneecho ""# nested forfor(( i = 1; i <= 5; i++ ))dofor(( j = 1; j <= 5; j++ ))doecho -n "$i"done#echo ""done



6、case

[root@u1 shell_learn]# sh caseshell.shcaseshell.sh: must input a command[root@u1 shell_learn]# sh caseshell.sh 11 is not a valid command[root@u1 shell_learn]# sh caseshell.sh deletedelete the db[root@u1 shell_learn]# sh caseshell.sh selectselect the db


内容

#!/bin/bash#comments# test caseif [ $# -ne 1 ]then echo "$0: must input a command"exit 1fiaction=$1case $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.shshell name args:funcshell.shall function args:-f foo barall function agrs_num 3the first arg : -fthe second arg : foo:shell name args:funcshell.shall function args:foo barall function agrs_num 2the first arg : foothe second arg : bar:


内容

#!/bin/bash#comments# test functionfunction 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:"shiftecho "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 functiondemo -f foo bar


8、date

[root@u1 shell_learn]# sh cmd_learn/date.sh[root@u1 shell_learn]# cat cmd_learn/date.log2015-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#commentsfind / -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.shdisplaydisplaydisplay         display :first name : qqsecond name :aliqq aliu1       tty1         2015-07-16 22:00u1       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 whwhileshell.sh  who.out[root@u1 shell_learn]# cat who.outu1       tty1         2015-07-16 22:00u1       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.log2015-07-22 11:57:59 1


内容

#!/bin/bash#echo cat read tee |#in--0  < <<#out--1 > >>#err--2 2>&1#echoecho "display"echo -e "display \n"echo -n -e "display \t"echo -e "display :\c"echo ""#readecho -e "first name : \c"read nameecho -e "second name :\c"read middleecho "$name $middle"#cat#cat -v  > cat_read.log#teewho | tee who.out#0 1 2echo "`date -d today +"%Y-%m-%d %T"`" 1 >> in_out.log 2>&1


11、read

[root@u1 shell_learn]# sh readshell.sh1.unix(sun os)2.linux(redhat)select your os choice [1 or 2] ?2you pick up linux[root@u1 shell_learn]# sh readshell.sh1.unix(sun os)2.linux(redhat)select your os choice [1 or 2] ?4what you donot like linux/unix


内容

#!/bin/sh#comments#define a variableosch=0#display promptecho "1.unix(sun os)"echo "2.linux(redhat)"echo -n "select your os choice [1 or 2] ?"#wait user inputread osch#ifif [ $osch -eq 1 ]thenecho "you pick up unix"else#nested ifif [ $osch -eq 2 ]thenecho "you pick up linux"elseecho "what you donot like linux/unix"fifi



12、rename file

[root@u1 shell_learn]# lsback_syncDeptFtp.sh  forshell.sh       ifshell.sh           syncDeptFtp.shcaseshell.sh         funcshell.sh      in_out.log           whileshell.shcmd_learn            getFtpFile.sh     multisyncDeptFtp.sh  who.outdata                 getSyncStatus.sh  readme.txtdebugshell.sh        helloshell.sh     readshell.shfind.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 *.shrenaming back_syncDeptFtp.sh to back_syncDeptFtp.SHrenaming caseshell.sh to caseshell.SHrenaming debugshell.sh to debugshell.SHrenaming forshell.sh to forshell.SHrenaming funcshell.sh to funcshell.SHrenaming getFtpFile.sh to getFtpFile.SHrenaming getSyncStatus.sh to getSyncStatus.SHrenaming helloshell.sh to helloshell.SHrenaming ifelshell.sh to ifelshell.SHrenaming ifshell.sh to ifshell.SHrenaming multisyncDeptFtp.sh to multisyncDeptFtp.SHrenaming readshell.sh to readshell.SHrenaming rename.sh to rename.SHrenaming syncDeptFtp.sh to syncDeptFtp.SHrenaming whileshell.sh to whileshell.SH[root@u1 shell_learn]# lsback_syncDeptFtp.SH  forshell.SH       ifshell.SH           syncDeptFtp.SHcaseshell.SH         funcshell.SH      in_out.log           whileshell.SHcmd_learn            getFtpFile.SH     multisyncDeptFtp.SH  who.outdata                 getSyncStatus.SH  readme.txtdebugshell.SH        helloshell.SH     readshell.SHfind.log             ifelshell.SH      rename.SH


内容

#!/bin/bash#comments# test rename fileif [ $# -lt 3 ] thencat<<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' *.shHELPexit 0fi#old=$1new=$2shiftshiftfor file in $* doif [ -f $file ]; thennewfile=`echo $file | sed "s/${old}/${new}/g"`if [ -f $newfile ] ;thenecho "error:$newfile exists already"elseecho "renaming $file to $newfile"mv $file $newfilefifidone


13、debug info

[root@u1 shell_learn]# sh -v debugshell.sh#!/bin/bash#comments# test debugtot=`expr $1 + $2`expr $1 + $2expr: 语法错误echo $tot[root@u1 shell_learn]# sh -v debugshell.sh 4 5#!/bin/bash#comments# test debugtot=`expr $1 + $2`expr $1 + $2echo $tot9


内容

#!/bin/bash#comments# test debugtot=`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 8080tcp        0      0 :::8080                     :::*                        LISTEN      60571/java          off (0.00/0/0)[root@u1 shell_learn]# ps -ef | grep psroot        41     2  0 Jul16 ?        00:00:00 [kpsmoused]root      1615     1  0 Jul16 ?        00:00:00 cupsd -C /etc/cups/cupsd.confroot     49227 39366  3 12:12 pts/3    00:00:00 ps -efroot     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 pathecho "uasge:`basename $0` file"exit 1[u1@u1 common]$ sh /home/u1/mtsd3/shell_learn/common/basename.shuasge:basename.sh file


tar

[u1@u1 common]$ cat tar.sh#!/bin/sh#tar options  filescp cat.sh cat1.shlstar -zcvf  cat.tar.gz cat1.shrm -f cat1.shlstar -zxvf cat.tar.gzls

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 filenamenl 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.shawk '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 test0Marry   2143 78 84 77Jack    2321 66 78 45Tom     2122 48 77 71Mike    2537 87 97 95Bob     2415 40 57 62


[root@u1 common]# sh awk.shLineno.   Name    No.    Math   English   Computer    Total------------------------------------------------------------1        Marry   2143    78      84        77         2392        Jack    2321    66      78        45         1893        Tom     2122    48      77        71         1964        Mike    2537    87      97        95         2795        Bob     2415    40      57        62         159------------------------------------------------------------Total:                   319     393       350Avg:                     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 readmysql tables in use 1, locked 1LOCK WAIT 4 lock struct(s), heap size 1248, 3 row lock(s)MySQL thread id 8574, query id 6854603 172.16.22.243 root statisticsselect 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 waitingRecord 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 readmysql tables in use 1, locked 14 lock struct(s), heap size 1248, 3 row lock(s)MySQL thread id 8575, query id 6854605 172.16.22.243 root statisticsselect 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 gapRecord 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 waitingRecord 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




0 0
原创粉丝点击