linux shell 脚本练习,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  "\

echo $i.stop

let sum1+=1

done

for j in $(ls /etc/rc.d/rc3.d/ | grep "\

echo $j.start

let sum2+=1

done

echo "There are $sum1 file names start with "K"."

echo "There are $sum2 file names start with "S"."

执行效果:

3c8ce6380daa33c267ccb0e2e66a02de.png

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."

运行效果:

3c8ce6380daa33c267ccb0e2e66a02de.png

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."

运行效果:

3c8ce6380daa33c267ccb0e2e66a02de.png

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

运行效果:

3c8ce6380daa33c267ccb0e2e66a02de.png

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."

3c8ce6380daa33c267ccb0e2e66a02de.png

原创文章,作者:N24_lantian,如若转载,请注明出处:http://www.178linux.com/63944

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值