书籍:鸟哥的私房菜Linux基础学习

13. 学习shell script

#!/bin/bash

echo -e 'Hello World! \a \n'

#时间的操作
date1=$(date --date='2 days ago' +%Y%m%d)
date2=$(date --date='1 days ago' +%Y%m%d)
date3=$(date +%Y%m%d)

#文件名的检测
read -p 'Please input filename: ' filename    #使用filename接受用户输入的参数
test -z ${filename} && echo 'not input filename' && exit 0    #如果输入的是空字符串就返沪True并打印提示信息退出

#文件名日期的拼接
filename=${filename:-'notinput'}
#判断用户是否输入文件名,如果输入了就用输入的,如果没有输入就用默认的notinput
echo ${filename}'_'${date2}'.log'
echo ${filename}'_'${date2}'.log'
echo ${filename}'_'${date3}'.log'

#运算式的编写
read -p 'input first num: ' firstnum
read -p 'input second num: ' secondnum
total=$((${firstnum}+${secondnum}))
echo ${total}

#使用中括号进行条件判断的时候注意格式的书写
read -p 'delete file ? (Y/N): ' yn
[ "${yn}" == "Y" -o "${yn}" == "y" ] && echo 'yes' && exit 0
[ "${yn}" == "N" -o "${yn}" == "n" ] && echo 'no' && exit 0

#参数的获取
echo "total param: --> $#"
echo "script name: --> $0"
echo "whole param: --> $@"

[ "$#" -lt 2 ] && echo "need more than 2 param, stoped..." && exit 0

echo "first param: --> $1"
echo "second param: --> $2"
echo "third param: --> $3"


#参数移除,向左移除
shift

echo "total param: --> $#"
echo "whole param: --> $@"


#if else 语句
read -p "mv file ? (Y/N): " yn
if [ "$yn" == "Y" ] || [ "$yn" == "y" ]; then 
    echo "begin mv file..."
    exit 0
elif [ "$yn" == "N" ] || [ "$yn" == "n" ]; then
    echo "do not mv file"
    exit 0
else
    echo "input error"
    exit 0
fi

#case 语句
#read -p "please input your choice: " choice
#case $choice in 
case $1 in 
    "one")
        echo "Your Choice is One"
        ;;
    "tow")
        echo "Your Choice is Two"
        ;;
    "three")
        echo "Your Choice is Three"
        ;;
    *)
        echo "Usage $0 {one|two|three}"
        ;;
esac


#使用function
function my_add(){
    echo "result: "$1"+"$2"="$(($1 + $2))
    return $(($1 + $2))
}

total=`my_add 1 2`    #total 的值为函数中输出的信息--> result: 1+2=3
echo "$?"    #"$?"的值为return的值--> 3
echo $total

#while 循环
while [ "$yn" != "YES" ] && [ "$yn" != "yes" ]
do
    echo "wait"
    read -p "Please input yes|YES to stop this program: " yn
done
echo "OK! You input the correct answer"

#for 循环
users=$(cat /etc/passwd | cut -d ':' -f 1)
for user in $users
do
    id $user
done

read -p "Please input a number, I will calcu 1+2+3+...+your inout: " nu
s=0
for ((i=1; i <$nu; i=i+1))
do
    s=$(($s+$i))
done
echo "1+2+3+...+$nu=$s"

  

 

posted @ 2018-02-23 14:41  桃源仙居  阅读(103)  评论(0)    收藏  举报