学习shell——练习题

声明:本文转自博客king+++,仅按自己习惯做部分修改。

练习一:
       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
#program
#set the value to FILE with "/etc/passwd" and say user hello with the format as "Hello,root,your UID is 0."
#history
#version 1.0
#etc

PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
FILE="/etc/passwd"
#number of the users
userNum=`wc -l  $FILE | cut -d ' ' -f1`
for line in $(seq 1 $userNum)
do
        username=`head -$line $FILE |tail -1 |cut -d: -f1`
        id=`head -$line $FILE |tail -1 |cut -d: -f3`
        echo "Hello,$username,your UID is $id."
done

      

练习二:

      1.切换工作目录至/var

      2.依次向/var目录中的每个文件或子目录问好,形如:
        (提示:for FILE in /var/*;或for FILE in `ls /var`;)
        Hello,log

      3.统计/var目录下共有多个文件,并显示出来

#!/bin/bash
#program
#simple demo
#history
#version 1.0
#etc

PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

cd /var

for FILE in `ls /var`
do
        echo "Hello $FILE"
done

echo `ls /var |wc -l`

练习三:

写一个脚本
      1.设定变量file的值为/etc/passwd
      2.使用循环读取文件/etc/passwd的第2,4,6,10,13,15行,并显示其内容

      3.把这些行保存至/tmp/mypasswd文件中

#!/bin/bash

file="/etc/passwd"

for se in 2 4 6 10 13 15
do
        head -$se $file |tail -1 |tee -a /tmp/mypasswd
done


re:

列出当前目录下以字母开头,后跟一个任意数字,而后跟任意长度字符的文件或目录

ls [[:alpha:]][[:digit:]]*


你可能感兴趣的:(学习shell——练习题)