Linux Bash Shell练习

Linux Bash Shell练习

1、写一个脚本,完成以下功能:

假设某目录(/etc/rc.d/rc3.d/)下分别有K开头的文件和S开头的文件若干

显示所有以K开头的文件的文件名,并且给其附加一个stop字符串

显示所有以S开头的文件的文件名,并且给其附加一个start字符串

分别统计S开头和K开头的文件各有多少

#!/bin/bash
#
for i in $(ls /etc/rc.d/rc3.d/ | grep  "

执行效果:

2、写一个脚本,完成以下功能:

脚本能接受用户名作为参数

计算这些用户的ID之和

#!/bin/bash
#
[ $# -eq 0 ] && echo "Please give one user name or more." && exit 1

for i in $*;do
for j in $(id -u $i);do
let sum+=$j
done
done

echo "Sum:$sum."

运行效果:

3、写一个脚本:

传递一些目录给此脚本

逐个显示每个目录的所有一级文件或子目录的内容类型

统计一共有多少个目录;且一共显示了多少个文件的内容类型

#!/bin/bash
#
[ $# -eq 0 ] && echo "At least give one file path." && exit 1

for j in  $*/*;do
if [ -b $j ];then
echo "$j is block file."
let sum1+=1
elif [ -c $j ];then
echo "$j is character file."
let sum1+=1
elif [ -d $j ];then
echo "$j is a directory."
let sum+=1
elif [ -f $j ];then
echo "$j is a common file."
let sum1+=1
elif [ -L $j ];then
echo "$j is a symbolic link."
let sum1+=1
elif [ -p $j ];then
echo "$j is a pipe file."
let sum1+=1
elif [ -S $j ];then
echo "$j is a socket file."
let sum1+=1
else
echo "$j is unknown file."
let sum1+=1
fi
done

let sum2=$sum+$sum1

echo "There are $sum directories."
echo "There are $sum2 files and directories."

运行效果:

4、写一个脚本

通过命令行传递一个参数给脚本,参数为用户名

如果用户的id号大于等于500,则显示此用户为普通用户

#!/bin/bash
#
[ $# -eq 0 ] && echo "At least one user name needed." && exit 1

for i in $*;do
if ! id $i &>/dev/null ;then
echo "No such user:$i" 
elif [ $(id -u $i) -ge 500 ];then
echo "$i is a common user."
fi
done

运行效果:

5、写一个脚本

添加10用户user1-user10,密码同用户名

用户不存在时才添加,存在时则跳过

最后显示本次共添加了多少用户

#!/bin/bash
#
declare -i sum=0

for i in {1..10};do
if id user$i &>/dev/null;then
echo "User user$i is exist."
else
useradd user$i &>/dev/null
echo "user$i" | passwd --stdin "user$i" &>/dev/null
echo "User user$i add finished."
let sum+=1
fi
done 

echo "There are $sum users added."

  • 版权声明: 本文源自互联网, 于3个月前,由整理发表,共 198字。
  • 原文链接:点此查看原文