zoukankan      html  css  js  c++  java
  • shell脚本练习

    一、练习分支

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

    case方案

    #!/bin/bash
    RED="33[31m" YELLOW="33[0;33m" RESET="33[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="33[31m" YELLOW="33[0;33m" RESET="33[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="33[31m" YELLOW="33[0;33m" RESET="33[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"
  • 相关阅读:
    谷歌开源计划
    windows XP/vista/win 7 开机登录密码破解大全
    QQ好友空间加密没有密码但我们又很想看怎么办?(QQ空间瞬间破解+相册破解)
    VMware Workstation 7.1.4385536官方正式版+完美汉化包+注册码
    win7/xp笔记本建立wifi热点 用手机连接上网
    Cisco路由器OSPF协议经典学习笔记
    宽带连接错误的处理办法691、623、678、645、720、721、718、734、769、619、676、815
    CCNA的综合实验2
    交换机故障的一般分类和排障步骤
    cisco_iso命名规则
  • 原文地址:https://www.cnblogs.com/tanxiaojun/p/10468210.html
Copyright © 2011-2022 走看看