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"