制作显示欢迎信息的脚本程序

终端程序恐怕是Linux用户使用最为频繁的了。我的Debian系统启动后便是直接进入的终端界面。为了在每次登录时或者是在X视窗环境下打开终端程序时显示一些欢迎信息,比如当前的日期、名人警句等,从而可以增加一些生活情趣,就可以创建一个脚本程序,然后在~/.bashrc文件调用它。我自己就写了一个welcome.sh,执行时首先显示当前登录的用户名与主机名,然后打印出当天的日期、当天处于今年的第几个星期——这一数据在项目汇报中常被使用。同时,显示当天是今年的第几天,计算出距离年末还有几天,这样就可以给自己警醒,“又一年即将过去,自己是否珍惜了时光?”。最后,脚本调用fortune程序,随机显示一些警句或有意思的话。将这些综合起来,写成welcome.sh脚本如下:

#!/bin/bash

script_name="welcome.sh"
script_usage=$(cat <<EOF
welcome.sh [OPTIONS]
EOF
)
script_function=$(cat <<EOF
Display a welcome message.
EOF
)
script_doc=$(cat <<EOF
-h     Display this help.
EOF
)
script_examples=$(cat <<EOF
EOF
)
state_prefix="==="
warning_prefix="***"
error_prefix="!!!"

function display_help() {
    if [ -n "$script_usage" ]; then
    echo -e "Usage: $script_usage"
    fi
    
    if [ -n "$script_function" ]; then
    echo -e "$script_function"
    fi
    
    if [ -n "$script_doc" ] ; then
    echo -e "
$script_doc"
    fi
    
    if [ -n "$script_examples" ]; then
    echo -e "
Examples"
    echo -e "$script_examples"
    fi
}

# Delete a same character from the beginning of a variable. The source variable is the global variable $src_string
# $1: pattern character
function del_leading_chars() {
    local pat_char
    local prev_src_string_len
    local src_string_len

    declare -i prev_src_string_len
    declare -i src_string_len

    pat_char=$1
    prev_src_string_len=0
    src_string_len=${#src_string}

    while [ $(($prev_src_string_len != $src_string_len)) = 1 ]; do
    prev_src_string_len=$src_string_len
    src_string=${src_string/#${pat_char}/}
    src_string_len=${#src_string}
    done
}

# Process command options
while getopts ":h" opt; do
    case $opt in
    h  )  display_help
        exit 0 ;;
    ? )  display_help
        exit 1 ;;
    esac
done
shift $(($OPTIND - 1))

# Start execute the command

declare -i total_dates=365
year=`date +%Y`

# Test leap year
if [ $(($year % 100 == 0)) = 1 ]; then
    if [ $(($year % 400 == 0)) = 1 ]; then
    total_dates=366
    fi
else
    if [ $(($year % 4 == 0)) = 1 ]; then
    total_dates=366
    fi
fi

src_string=`date +%j`
del_leading_chars '0'
cur_day_no=$src_string
src_string=`date +%V`
del_leading_chars '0'
cur_week_no=$src_string

echo "********************************************************"
echo "Hello "`whoami`"! ""Welcome to "`hostname`"!"
echo "Today is "`date "+%A, %B %d, %Y"`
echo "Week $cur_week_no, day $cur_day_no, remaining days $(($total_dates - $cur_day_no))"
echo "********************************************************"
fortune

welcome.sh放入~/.bashrc后,现在再打开终端程序,就会显示出现面的信息:

原文地址:https://www.cnblogs.com/quantumman/p/4586756.html