輸入和字符串
#!/bin/bash
#使用$#輸出參數(shù)的格數(shù)
echo "We have $# parameters."
#按順序輸出參數(shù)
echo $0 $1 $2
#輸出$*和$@
echo $*
echo $@
OLD="I am an old boy"
echo "The parameter number is $#"
echo "The string length is ${#OLD}"
echo "The string start 2 is ${OLD:2}"
echo "The string start 2 with length 5 is ${OLD:2:5}"
echo "We can seperate the string by the whitespace"
set -- $OLD
echo "The fifth word is $5"
計算
#!/bin/bash
echo "This is a smaple to do the calculation in shell"
((a=1+2**3-4%3))
echo "The value of a in ((a=1+2**3-4%3)) is: $a"
echo "Now use the varibles"
i=2
let i=i+8
echo $i
echo "Now use the expr"
expr 2 + 2
expr 3 \* 3
expr 1+1
echo "Now we use the bc, bc is a calculator"
echo 1+1 | bc
echo 2^10 | bc
變量讀取
#!/bin/bash
echo "We'll read a prameter from the input with timeouut 5s"
read -t 5 -p "Please input:" a
if [ -z "$a" ];then
echo "You didn't input anything"
else
echo $a
fi
數(shù)字的比較
#!/bin/sh
read -p "Pls input two num:" a b
#Shell中使用[]作為判斷語句,這時中括號兩側必須有空格董虱。在Shell中有時空格要求比較嚴格,切記切記
[ -z "$a" ] || [ -z "$b" ] && {
echo "Pls input two num again."
exit 1
}
expr $a + 0 &> /dev/null
#在bash中,賦值不能加空格矢腻,這個跟其他語言不太一樣
retval1=$?
echo $retval1
expr $b + 0 &> /dev/null
retval2=$?
echo $retval2
test $retval1 -eq 0 -a $retval2 -eq 0 || {
echo "Pls input two nums again"
exit 2
}
[ $a -lt $b ] && {
echo "$a < $b"
exit 0
}
[ $a -gt $b ] && {
echo "$a > $b"
exit 0
}
[ $a -eq $b ] && {
echo "$a = $b"
exit 0
}