第一个shell程序

第一次写shell程序,写了一些简单的代码,稍微介绍一下。

首先程序以#!/bin/bash指定shell是Bourne Again Shell(shell的一种,若是#!/bin/tcsh开头则说明指定的是TCshell),紧接着第二行是一行注释,说明这个程序的功能等,当然可以不写,但是注释是一个良好的编程习惯。后面分别操作了字符串,变量运算,if,case,select,while,for和函数。

#!/bin/bash

#this is my first shell
echo "============string============="
str="this is my first shell"
echo "$str"
echo "==============var=============="
a=1
echo "the raw a=$a"
let "a+=1"
echo "ater let a=$a"
a=$[$a+1]
echo "ater [] a=$a"
((a++))
echo "ater ((++)) a=$a"
a=$(($a+1))
echo "ater ((+1)) a=$a"
a=$(expr $a + 1)
echo "ater expr  a=$a"
echo "==============if=============="
echo "input b:"
read b
if [ $b -eq 0 ]
then
    echo "$b=0"
elif [ $b -lt 1 ]
then
    echo "$b<0"
else
    echo "$b>0"
fi

echo "==============case=============="
echo "input d:"
read d
if [ $d -gt 7 ]
then
  d=$(($d%7))
fi
echo "d=$d"
case $d in
    1)echo "$d is Monday";;
    2)echo "$d is Tuesday";;
    3)echo "$d is Wednesday";;
    4)echo "$d is Thursday";;
    5)echo "$d is Friday";;
    6)echo "$d is saturday";;
    7)echo "$d is sunday";;
    *)echo "never come here";;
esac

echo "==============select=============="
echo "What is your favourite OS?"
select var in "Linux" "Windows" "Free BSD" "Other";do
    break;
done
echo "You have select $var"

echo "===============while==============="
echo "input m"
read m
#将sum设置成整形
typeset -i sum=0
while [ $m -gt 0 ]
    do
        sum+=$m
        ((m--))
    done
echo "after while sum=$sum"

echo "================for================"
sum=0
for m in 1 2 3 4 5 6 7 8 9;
do
    sum+=$m
done
echo "after for sum=$sum"

echo "==============function=============="
function show()
{
    echo "show function"
}
$(show)
学习网址:http://wiki.ubuntu.org.cn/Shell%E7%BC%96%E7%A8%8B%E5%9F%BA%E7%A1%80

你可能感兴趣的:(shell)