几个shell例子

本文介绍了几个实用的Bash脚本实例,包括显示当前用户信息和目录、计算距离生日的天数、累加输入整数内的所有数字、管理文件与目录及解析passwd文件等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:http://houlei623.blog.sohu.com/140417273.html

 

  • 請建立一支 script ,當你執行該 script 的時候,該 script 可以顯示: 1. 你目前的身份 (用 whoami ) 2. 你目前所在的目錄 (用 pwd)
    #!/bin/bash
    echo -e "Your name is ==> $(whoami)"
    echo -e "The current directory is ==> $(pwd)"
  • 請自行建立一支程式,該程式可以用來計算『你還有幾天可以 過生日』啊?
    #!/bin/bash
    read -p "Pleas input your birthday (MMDD, ex> 0709): " bir
    now=`date +%m%d`
    if [ "$bir" == "$now" ]; then
    echo "Happy Birthday to you!!!"
    elif [ "$bir" -gt "$now" ]; then
    year=`date +%Y`
    total_d=$(($((`date --date="$year$bir" +%s`-`date +%s`))/60/60/24+1))
    echo "Your birthday will be $total_d later"
    else
    year=$((`date +%Y`+1))
    total_d=$(($((`date --date="$year$bir" +%s`-`date +%s`))/60/60/24+1))
    echo "Your birthday will be $total_d later"
    fi
  • 讓使用者輸入一個數字,程式可以由 1+2+3... 一直累加到使用者輸入的數字為止。
    #!/bin/bash
    read -p "Please input an integer number: " number
    i=0
    s=0
    while [ "$i" != "$number" ]
    do
    i=$(($i+1))
    s=$(($s+$i))
    done
    echo "the result of '1+2+3+...$number' is ==> $s"
  • 撰寫一支程式,他的作用是: 1.) 先查看一下 /root/test/logical 這個名稱是否存在; 2.) 若不存在,則建立一個檔案,使用 touch 來建立,建立完成後離開; 3.) 如果存在的話,判斷該名稱是否為檔案,若為檔案則將之刪除後建立一個目錄,檔名為 logical ,之後離開; 4.) 如果存在的話,而且該名稱為目錄,則移除此目錄!
    #!/bin/bash
    if [ ! -e logical ]; then
    touch logical
    echo "Just make a file logical"
    exit 1
    elif [ -e logical ] && [ -f logical ]; then
    rm logical
    mkdir logical
    echo "remove file ==> logical"
    echo "and make directory logical"
    exit 1
    elif [ -e logical ] && [ -d logical ]; then
    rm -rf logical
    echo "remove directory ==> logical"
    exit 1
    else
    echo "Does here have anything?"
    fi
  • 我們知道 /etc/passwd 裡面以 : 來分隔,第一欄為帳號名稱。請寫一隻程式,可以將 /etc/passwd 的第一欄取出,而且每一欄都以一行字串『The 1 account is "root" 』來顯示,那個 1 表示行數。
    #!/bin/bash
    accounts=`cat /etc/passwd | cut -d':' -f1`
    for account in $accounts
    do
    declare -i i=$i+1
    echo "The $i account is /"$account/" "
    done

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值