shell脚本练习

一、练习分支

编写脚本/root/bin/createuser.sh,实现如下功能:使用一个用户名做为参数,如果指定参数的用户存在,就显示其存在,否则添加之;显示添加的用户的id号等信息

case方案

#!/bin/bash
RED="\033[31m" YELLOW="\033[0;33m" RESET="\033[0m" if [ $# -ne 1 ] ; then echo -e "$REDyou must be enter a parameter ,only one!$RESET" exit 2 fi username=$1 id $username &>/dev/null if [ $? -eq 0 ] ; then echo -e "$YELLOW$username has existed !$RESET" else useradd $username &>/dev/null fi id $username

编写脚本/root/bin/yesorno.sh,提示用户输入yes或no,并判断用户输入的是yes还是no,或是其它信息

#!/bin/bash
read -p "do you agree (yes/no):" choice case $choice in [Yy]|[Yy][Ee][Ss]) echo "you enter a yes" ;; [Nn]|[Nn][Oo]) echo "you enter is no" ;; *) echo "not yes or no " ;; esac

if方案

#!/bin/bash
read -p "do you agree (yes/no):" choice yes_re="^[Yy]([Ee][Ss])?$" no_re="^[Nn]([Nn])?$" if [[ "$choice" =~ $yes_re ]] ; then echo "you enter yes" elif [[ "$choice" =~ $no_re ]] ; then echo "you enter no " else echo "enter not a yes or no " fi

 编写脚本/root/bin/filetype.sh,判断用户输入文件路径,显示其文件类型(普通,目录,链接,其它文件类型)

#!/bin/bash
RED="\033[31m" YELLOW="\033[0;33m" RESET="\033[0m" if [ $# -ne 1 ] ; then echo -e "$REDyou must be enter a parameter ,only one!$RESET" exit 2 fi file=$1 type=`ls -ld $file |cut -c 1` #echo $type case $type in -) echo "general file" ;; d) echo "dir" ;; l) echo "link file" ;; *) echo "other" ;; esac

 

编写脚本/root/bin/checkint.sh,判断用户输入的参数是否为正整数

#!/bin/bash
RED="\033[31m" YELLOW="\033[0;33m" RESET="\033[0m" if [ $# -ne 1 ] ; then echo -e "$REDyou must be enter a parameter ,only one!$RESET" exit 2 fi val=$1 int_re="^[0-9]+$" if [[ $val =~ $int_re ]] ; then echo "yes" else echo "no" fi

二、练习循环

写一个脚本

1.脚本可以接受一个以上的文件路径作为参数;

2.显示每个文件所拥有的行数

3.显示本次共对多少个文件执行了行数统计

#!/bin/bash
for file in $*;do
    lines=`wc -l $file|cut -d' ' -f1` echo "$file has $lines lines." done

判断/var/目录下所有文件的类型

#!/bin/bash
dir="/var" for i in $(ls -1 $dir) ; do type=`ls -ld $file |cut -c 1` echo -n "$dir/$i===============>" case $type in -) echo "general file" ;; d) echo "dir" ;; l) echo "link" ;; s) echo "socket" ;; b) echo "block" ;; c) echo "character" ;; *) echo "other" ;; esac done

添加10个用户user1-user10,密码为8位随机字符

#!/bin/bash
for
i in `seq 1 10` ; do username=user$i useradd $username echo `openssl rand -base64 10| head -c 8` | passwd $username --stdin &>/dev/null done echo "finish"

 

转载于:https://www.cnblogs.com/tanxiaojun/p/10468210.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值