shell脚本例子集锦

练习一:写一个脚本
      1.设定变量FILE的值为/etc/passwd
      2.依次向/etc/passwd中的每个用户问好,并且说出对方的ID是什么
       形如:(提示:LINE=`wc -l /etc/passwd | cut -d" " -f1`)
        Hello,root,your UID is 0.
      3.统计一个有多少个用户
    答案一:#!/bin/bash
          file="/etc/passwd"
          LINES=`wc -l $file | cut -d" " -f1`
          for I in `seq 1 $LINES`;do
          userid=`head -$I $file | tail -1 |cut -d: -f3`
          username=`head -$I $file | tail -1 |cut -d: -f1`
          echo "hello $username,your UID is $userid"
          done
          echo "there are $LINES users"
    答案二:#!/bin/bash
          file=/etc/passwd
          let num=0
          for I in `cat $file`;do
          username=`echo "$I" | cut -d: -f1`
          userid=`echo "$I" | cut -d: -f3`
          echo "Hello,$username,your UID is $userid"
          num=$[$num+1]
          done
          echo "there are $num users"
练习二:写一个脚本
     1.切换工作目录至/var
     2.依次向/var目录中的每个文件或子目录问好,形如:
       (提示:for FILE in /var/*;或for FILE in `ls /var`;)
       Hello,log
     3.统计/var目录下共有多个文件,并显示出来
  答案:#!/bin/bash
        cd /var
    

你可能感兴趣的:(shell脚本例子集锦)