Shell 编程入门
优质博文:IT-BLOG-CN
【1】x.sh文件内容编写:固定开头:#!/bin/sh;
【2】学习的第一个命令就是 echo输出的意思;
【3】其实 shell脚本也就是在文件中写命令,但是我们要写的是绝对路径:eg:/bin/pwd;
【4】运行shell脚本:sh 文件名;
【5】通过下面脚本进行学习:
1 #!/bin/sh 2 /bin/date +%F >> /test/shelldir/ex2.info #data +%F是将日期格式化。>>追加输出 3 echo "disk info:" >> /test/shelldir/ex2.info 4 /bin/df -h >> /test/shelldir/ex2.info 5 echo >> /test/shelldir/ex2.info 6 echo "online users:" >> /test/shelldir/ex2.info 7 /usr/bin/who | /bin/grep -v root >> /test/shelldir/ex2.info #使用的命令主要来自两个地方:①、/bin/ ②、/usr/bin/ -v:表示排除 8 echo "memory info:" >> /test/shelldir/ex2.info 9 /usr/bin/free -m >> /test/shelldir/ex2.info 10 echo >> /test/shelldir/ex2.info 11 #write root 12 /usr/bin/write root < /test/shelldir/ex2.info && /bin/rm /test/shelldir/ex2.info 13 crontab -e #定时执行命令 14 0 9 * * 1-5 /bin /sh /test/ex2.sh #表示:每周一到周五的9点执行该脚本。
【6】变量:是shell传递数据的一种方式,用来代表每个取值的符号。Shell的变量有两种:①、永久变量 ②、临时变量。临时变量是shell程序内部定义的,其使用范围只限于定义它的程序,其它程序不可见。包括程序自定义变量、位置变量。永久变量是环境变量。其值不随 shell脚本的执行结束而消失。
【永久变量】:
1 #!/bin/sh 2 DATE=`/bin/date +%Y%m%d` 3 echo "TODAY IS $DATE" 4 /bin/ls -l $1 5 /bin/ls -l $2 6 /bin/ls -l $3
在命令行输入:sh 文件名 /test /usr/bin /home。解释:就是让命令中的/test替换脚本中的$1........
【8】特殊变量:
■ $* 这个程序的所有参数;
■ $# 这个程序的参数个数;
■ $$ 这个程序的PID;
■ $! 执行上一个程序的PID;
■ $? 执行上一个命令的返回值;
■ $(0-9)显示位置变量;
【9】read:键盘输入,命令:read 从键盘读取数据,赋给变量。
1 #!/bin/sh 2 read f s t 3 echo "the first is $f" 4 echo "the second is $s" 5 echo "the third is $t"
执行命令:sh 文件名先执行,在输入变量。如果输入:sh -x 文件名执行 shell脚本,当执行到 read时会弹出:read f s t,然后我们根据需求输入,例如:10 20 30;
【10】shell的运算:expr命令,对整数进行运算。注意点:
①、expr的计算必须用空格隔开;
②、\*表示转义字符;
③、保持先算乘除后算加减,如果需要优先算法需要加命令替换符;
④、可以对变量进行运算;
【11】test测试命令:使用 test命令可以对文件、字符串等进行测试,一般配合控制语句使用,不应该单独使用。
【12】if 语句,语法格式:
1 if [ -d $1 ] 2 then 3 else 4 fi
【实例展示】
1 #!/bin/sh 2 # if test $1 then ... else ... fi 3 if [ -d $1 ] 4 then 5 echo "this is a directory!" 6 else 7 echo "this is not a directory!" 8 fi
【if elif 语法】
1 #!/bin/sh 2 # if test then ... elif test then ... else ... fi 3 if [ -d $1 ] 4 then 5 echo "is a directory!" 6 elif [ -f $1 ] 7 then 8 echo "is a file!" 9 else 10 echo "error!" 11 fi
【逻辑 与-a 和 或-o】
1 #!/bin/sh 2 # -a -o 3 if [ $1 -eq $2 -a $1 = 1 ] 4 then 5 echo "param1 == param2 and param1 = 1" 6 elif [ $1 -ne $2 -o $1 = 2 ] 7 then 8 echo "param1 != param2 or param1 = 2" 9 else 10 echo "others" 11 fi
【for循环】
1 #!/bin/sh 2 # for var in [params] do ... done 3 for var in 1 2 3 4 5 6 7 8 9 10 4 do 5 echo "number is $var" 6 done
【select循环】
1 #!/bin/sh 2 # select var in [params] do ... done 3 select var in "java" "c++" "php" "linux" "python" "ruby" "c#" 4 do 5 break 6 done 7 echo "you selected $var"
【case循环】
1 #!/bin/sh 2 read op 3 case $op in 4 a) 5 echo "you selected a";; 6 b) 7 echo "you selected b";; 8 c) 9 echo "you selected c";; 10 *) 11 echo "error" 12 esac
【while循环】
1 #!/bin/sh 2 #while test do ... done 3 4 num=1 5 sum=0 6 while [ $num -le 100 ] #le表示小于等于 7 do 8 sum=`expr $sum + $num` 9 num=`expr $num + 1` 10 done 11 #sleep 5 12 echo $sum