我的linux学习8 shell脚本

时间:2022-07-24 15:33:47

如果用到数字计算:var=$((运算内容))这种方法不需要定义类型,而且方便。

获得前天的时间:date --date='1 days ago' +%Y%m%d

 

使用test测试功能: 如test -efilename  (以下为常用的)

-e 该文件名是否存在

-f 是否为文件

-d 是否为目录

-r 是否可读   -w是否可写  -x 是否可执行

-nt判断2文件新    test file1 -ntfile2          判断file1是否比file2新

-ot判断2文件旧    test file1 -otfile2          判断file1是否比file2旧

-ef 判断2文件是否为同一文件  ,主要用于判断硬链接

两个整数间的判断: test n1 -eq n2

-eq 两数相等

-ne  不相等

-gt 大于   -lt小于

-ge 大于等于   -le小于等于

判断字符串数据:

test -z string 判断字符串是否为0,若字符串为空,则为true

test -n string 判断字符串是否为非0,若字符串不为空,则为true

test str1 = str2 判断str1是否等于str2 ,若相等,则返回true

test str1 != str2 判断str1是否等于str2 ,若不相等,则返回true

多重条件判断: test -r filename -a -x filename

-a 并且

-o 或

!反        test! -xfile,当file不具有执行,返回true

例子为:sh05.sh

 

除了使用test外,还可以使用 [ ]来判断 ,例如判断$HOME是否为空 [ -z "$HOME"]

特别注意:使用[ ]在每个组件中都要有空格  [ "$HOME" =="$MAIL" ],变量最好用双引号,常量最好用单引号或双引号

 

Shell脚本的默认变量($0,$1......)

$0 :代表脚本名(含路径)

$1~$n :代表脚本的第几个参数

 

条件判断:

if [ 条件判断 ]; then

            命令

fi

 

if [ 条件判断 ]; then

           命令。

elif [ 条件判断 ]; then

           命令。

else

          命令。

fi


netstat:这个命令查看当前主机是否有打开的网络服务端口,可以利用netstat -tuln获取主机启动服务。

几个常用的端口:

80:www

22:shh

21:ftp

25:mail

例子在:sh09.sh

 

例子:让用户输入退伍日期,然后得到还有多久退伍。  sh10.sh

 

 

使用case....esac判断

case $变量 in

  "第一个判断")

       程序段

          ;;

  "第二个判断")

       程序段

          ;;

   *)

      程序段

         ;;

 esac

例如:sh08-2.sh

case$1 in
 "hello")
       echo 'Hello,how are you!!!'
       ;;  
 "") 
       echo "you must input parameters"
       ;;  
 *)
       echo "the parameters is not hello"
       ;;  
esac


函数也拥有内置变量:$0表示函数名,后续的变量用$1,$2.....来表示
 functionprintit(){
      echo -n "Your choice is $1 "
 }
printit1              ====================     Your choice is 1


循环

while [ condition ]
do
   程序段落
done
例子:sh13.sh


until [ contidion ]
do
   程序段落
done

 

 

for (( 初始值;限制值;执行步长))

do

    程序段落

done

例子:sh15.sh

total=0
for(( i=1;i<=100;i++ ))
do
       total=$(($total+$i))
done
echo "total=" $total

for的另一种用法:
for var in con1 con2 con3......
do
    程序段
done
例子:sh16.sh

Shell脚本的追踪与调试
sh [-nvx] scripts.sh :-n不要执行脚本,仅查询语法问题,-v在执行脚本前,先将脚本内容输出到屏幕上,-x将使用的脚本内容显示到屏幕上,这是很有用的参数。