shell 脚本 学习案例解析

昨天大约花了一天的功夫整理了一些shell脚本语言中语法知识,顺便写了很多的案例,分享给大家!

#!/bin/sh
echo "This is the first shell script!"
#=============This is comment.============
#==================变量===================
a="hello world!"
echo $a
echo "I am student. $a"
#=================算术运算=================
#加法
num=1
let num1=num+1
num2=$[ $num + 1]
num3=`expr $num + 1`
num4=$(($num + 1))
echo $num1 $num2 $num3 $num4
#乘法
r=`expr 4 \* 5` 
r=$(( 4 * 5 ))
r=$[ 4 * 5 ]
echo $r
#除法
r=`expr 40 / 5` 
r=$(( 40 / 5 ))
r=$[ 40 / 5 ]
echo $r
#================控制语句===================
#判断控制语句-if
if [ "$SHELL" = "/bin/bash" ]; then
    echo "your login shell is the bash"
else
    echo "your login shell is not bash but $SHELL"
fi
#判断控制语句-case
caseVar="a"
case $caseVar in
"a")
    echo "this is a";;
"b")
    echo "this is b";;
"c")
    echo "this is c";;
 * )
    echo "this is not an alphbet";;
esac
#选择控制语句-select
echo "What is your favourite OS?" 
select var in "Linux" "Gnu Hurd" "Free BSD" "Other"; do 
    break 
done 
echo "You have selected $var"
#循环控制语句-while
whileVar=1
while (( $whileVar != 10 )); do
    echo $whileVar
    whileVar=$(($whileVar+1))
done
#循环控制语句-for
for var in A B C ; do 
    echo "var is $var" 
done
#==============函数===================
function fSum()
{
    echo $1, $2;
    return $(($1+$2));
}
fSum 1 2
echo "functionResult=$?"
#=============实例====================
#1.计算10的阶乘
factorial=1
for a in `seq 1 10`; do
    factorial=$(($factorial * $a))
done
echo "10! = $factorial"
#2.执行后,打印一行提示“Please input a number:",
#  要求用户输入数值,然后打印出该数值,然后再次要求
#  用户输入数值。直到用户输入"end"停止
unset var
while [ "$var" != "end" ]; do
    echo -n "please input a number: "
    read var
    if [ "$var" = "end" ]; then
        break
    fi
    echo "var is $var"
done
#============命令行参数===============
# $0为程序路径和名称,$1 ...$9 ${10}参数
# $#参数的个数
echo `basename $0`
if [ $# != 2 ]; then
    echo "parameters must two!"
fi



你可能感兴趣的:(操作系统(OS),shell,脚本语言,实例)