数值累加
```shell
#!/bin/bash
read -p "please input a number: " num
s=0
for (( i=1;i<=$num;i++ ))
do
s=$(( $s+$i ))
done
echo "the sum is : $s"
```
---
字符串拼接
```shell
#!/bin/bash
# shell script
read -p "please input the firstname : " firstname
read -p "the lastname , please : " lastname
echo -e "\nthe name is : $firstname $lastname"
```
---
数值计算 (加,乘)
```shell
#!/bin/bash
# the compute numbers
read -p "input a number : " num
read -p "input another number : " num2
declare -i sum=$(($num+$num2))
echo -e "the sum of the two nums is $sum"
echo -e "the multiply of the two nums is $(( $num * $num2 ))"
```
---
测试参数1中的文件是否存在
```shell
#!/bin/bash
# test the file exist
test -e $1 && echo "exist !" || echo "not exist !"
```
---
if elif else 判定语句
```shell
#!/bin/bash
# the script show us how to if else
if [ "$1" == "hello" ]; then
echo "Hello,how are you!"
elif [ "$1" == "" ]; then
echo "You must input a param !"
else
echo "The only legal param is 'hello'"
fi
```
---
case判定 类似java switch 不过不需要用switch
```shell
#!/bin/bash
# the case judgement test
# case in esac
# the case judgement according to the case order
case $1 in
"hello") # the param "hello"
echo "hello,how are you! bro!?"
;;
"") # the empty param
echo "you must input a param like> {$0 param}"
;;
1)
echo "the number 1 is good"
;;
2)
echo "the number 2 is good"
;;
3)
echo "the number 3 is good"
;;
*) # the wildcard
echo "usage $0 {hello}"
;;
esac
```
---
启动和关闭redis
```shell
#!/bin/bash
# to quickly start redis
Resource_Name=/etc/init.d/redis
# first command symbol
cmd=$1
tpid=`ps -ef|grep $Resource_Name |grep -v grep|grep -v kill|awk '{print $2}'`
if [[ -z $cmd ]];then
echo 'error,usage{ sh $0 1|0 to start or stop this redis}'
elif [[ $cmd -eq 1 ]];then
$Resource_Name start
echo $! > tpid
echo 'Start Redis Success!~~~'
elif [[ $cmd -eq 0 ]];then
echo '[test] Stop Redis Process'
kill -15 $tpid
sleep 5
echo 'Kill Redis Processing!~~~'
kill -9 $tpid
echo 'Stop Redis Success!'
else
echo 'error!just 1 or 0 behind $0, like (sh $0 1)'
fi
```
---
启动和关闭java的war包
```shell
#!/bin/bash
#by ukzqmooc
#time: 2019-10-22 14:40
#to quickly start the java war
resource_name=test20191024-8085.war
cmd=$1
tpid=`ps -ef|grep $resource_name|grep -v grep|grep -v kill|awk '{print $2}'`
#logic shell code follow
if [[ -z $cmd ]];then
echo "err!usage{sh $0 1|0 to start or shutdown the test20191024-8085.war.}"
elif [[ $cmd -eq 1 ]];then
nohup java -jar $resource_name > test20191024-8085.log 2>&1 &
elif [[ $cmd -eq 0 ]];then
echo '<d83d><dc80> stop the war processing~'
kill -15 $tpid
sleep 5
echo 'kill the war processing !'
kill -9 $tpid
echo 'stop the war success !'
else
echo "err!just 1 or 0 behind $0,like(sh $0 1)"
fi
```
其他可参考
https://blog.csdn.net/zhangerqing/article/details/42914815
https://www.cnblogs.com/aaronLinux/p/8340281.html