linux shell脚本快速入门

  本文里,通过对shell脚本里的变量申明、循环语句、条件判断、数据叠加的总结,能解决linux日常管理的大部分脚本

1、变量的申明:

是弱类型的语言,用name=xxx;取变量值的时候$name

 

2、条件判断:

   if[ condition]; then

    operator;

   elif[ condition]; then

    operator;

   else

    operator;

   fi

3、循环:

  while[ condition]

#condition如果是用[]取代test,则有两个[]

  do

    operator;

  done;


 

  for((i=1;i<100;i++))

  do

     operator;

  done;


 

  for var in $(seq n)

#or for var in `cat /etc/hosts`

  do

     operator;

  done;

4、使用"[]"做判断条件注意点:

  1)、每个组件之间都要用空格隔开,如果用@代替空格,则表达式的判断为@[@str1@==@str2@]@;

  2)、用'=='进行判断时,两边的必须是字符串,所以必须用""括起来,如"$name" == "want",用$name == "want"出错,两边类型不同;

  3)、test判断:

    文件侦测: test -e filename

        test -f filename

        test -d direct

 

    文件权限判断:

        test -r filename

        test -w filename

        test -x filename

 

    文档时间:

        test file1 -nt file2;  判断file1是否比file2新

        test file1 -ot file2;

        test file1 -et file2;判断两个文件是否为同一个档案,可用在hard link的判断上

 

    两整数的判断:

        test n1 -eq n2;

        test n1 -ne n2;

        test n1 -gt n2;

        test n1 -lt n2;

        test n1 -ge n2;

        test n1 -le n2;

 

 

    字符串的判断:

      test -z string;字符串是否为空为0,如果string为空,则为true;

      test -n string;字符串是否非0

      test st1 = st2;

      test st1 != st2;

 

    多重判断:

      -a:and,例子test -r file -a -x file;

      -o:

      !:test ! -x file:判断file文件是否没有可执行权限

 

   4)、[]判断可以替代test进行判断,除了2)中的字符串相等要用==;

 

   5)、let "count=$count + 1";必须有"",否则出错

5、字符运算

  i=2;

  i=$(($i*2));

6、awk:

  awk '条件类型1{动作1} 条件类型2{动作2}' filename

   

  打印file中以分号分割的第三列大于10的第一列和第4

 

  cat file| awk 'BEGIN {FS=":"} $3 > 10 {print $1 "\t" $4}}

 

7、简单的例子:

  看完了这些,你是否可以写出这样的脚本了呢:用递归的思想找出给定目录下文件大小超过给定大小文件的脚本,虽然可以用find命令操作,但是还是值得动手去做的!

原文地址:https://www.cnblogs.com/uttu/p/2909067.html