shell脚本编写
shell语法
summary
编写shell脚本时,需要声明这是一个脚本文件
#!/bin/bash
声明作者,和编写日期。
NOTE: 尽可能详细的写出脚本的功能,做好注释。shell的可读性不是很好,因此强烈建议编写注释。
Hello World
#!/bin/bash
# this is a annotation
# auto echo hello world!
# by authors nulijiushimeili 2015
echo "hello world!"
echo -e "\033[32mPlease select Menu follow:\033[0m"
echo "1)installing apache server."
echo "2)installing mysql server."
echo "3)installing php server."
echo "4)deploying lamp web goals."
echo -e "\033[32m-----------------------------------------\033[0m"
获得执行的结果信息
- 当状态码等于0时表示执行成功,否则表示命令执行失败
#!/bin/bash
# 测试一条命令的执行结果
# 2019-02-19
service iptables stop
# 第一种写法,-eq 表示 =
if [ $? -eq 0 ]; then
echo "success!"
else
echo "failed!"
fi
# 第二种写法,-ne 表示 !=
if [ $? -ne 0 ]; then
echo "failed!"
else
echo "success!"
fi
- 将命令执行的结果返回给一个变量。
#!/bin/bash
# 得到执行命令的结果
res=`ps -ef | grep mysql-server`
echo $res
变量的使用
#!/bin/bash
# define path variables
name="Tom"
echo "$name"
echo "This is my name $name."
# shell process id.
echo $UID
# shell home
echo $PWD
echo "#######################"
# the first paramiter
echo $0
# the second paramiter
echo $1 $2
echo "#########################"
# expresses shell running ok
echo "The \$? is $?"
# get all parameters
echo "The \$* is $*"
# return how much params
echo "The \$# is $#"
if 语句
#!/bin/bash
# auto if test
# by author nulijiushimeili 2015
num1=$1
num2=$2
if (($#<2));then
echo "Usage: if.sh param1 param2."
echo "wrong input !!!"
else
if(($num1>$num2));then
echo "This $num1 greate $num2 !"
elif(($num1<$num2));then
echo "This $num1 little $num2 !"
else
echo "The $num1 equals $num2 !"
fi
fi
# check and mkdir
dir=temp
if [ ! -d $dir ];then
mkdir -p $dir
echo "create dir $dir success!"
else
echo "$dir is exists."
fi
elseif 语句
#!/bin/bash
# if else test demo
# by author nulijiushimeili
scores=$1
if (($#>0));then
if [[$scores -gt 85]];then
echo "Very good!";
elif [[$scores -gt 70]];then
echo "good";
elif [[$scores -gt 60]];then
echo "pass";
else
echo "so bad!";
fi
else
echo "Usage: elif.sh param1";
fi
for语句
#!/bin/bash
# test for
# by author nulijiushimeili 2015
# first test
for i in {1..5}
do
echo $i
done
# second test
for i in 6 7 8 9 10
do
echo $i
done
# third test
for FILE in $HOME/*
do
echo $FILE
done
# high order usage
for((i=0;i<10;i++))
do
echo $i
done
while 语句
#!/bin/bash
# test while loop
# by author nulijiushimeili
# print number from 1 to 5
counter=0
while [ $counter -lt 5 ]
do
counter=`expr $counter + 1`
echo $counter
done
# print input number in while loop
echo "please input a number."
echo "ctrl + d to exit."
while read FILM
do
echo "Yeah! great film the $FILM"
done
case语句
#!/bin/bash
# test case
# by author nulijiushimeili 2015
#if(($#>0))
if [ $# -gt 0 ]
then
case $1 in
1)
echo "one"
;;
2)
echo "two"
;;
3)
echo "three"
;;
4)
echo "four"
;;
*)
echo -e "\033[32mNothing to matched.\033[0m"
;;
esac
else
echo "Must to input a number parameter."
echo "please input a number in {1,2,3,4}."
echo "Usage: case.sh 1"
fi
shell函数
#!/bin/bash
# test function
# by author nulijiushimeili
# 声明一个方法
print(){
echo "hello word."
}
# 调用方法
print
test(){
num1=3
num2=4
return $(($num1 + $num2))
}
test
result=$?
echo $result
按行读取文件
#!/bin/base
# read file and get each line
# by author nulijiushimeili 2017
# -r express : allow special charactor
while read -r line
do
echo $line
done </opt/datas/emp.txt
# test add
i=1
sum=0
while ((i<10))
do
sum=$((sum=i+$sum))
i=$[i+1]
done
echo $sum
shell 编程知识
输出带颜色的打印信息
# 输出带颜色的打印信息
echo -e "\033[32m------\033[0m"
# 输出黑底白字的信息
echo -e "\033[40,37m------\033[0m"
字体颜色设置
# 字体颜色设置
echo -e “\033[30m 黑色字 \033[0m”
echo -e “\033[31m 红色字 \033[0m”
echo -e “\033[32m 绿色字 \033[0m”
echo -e “\033[33m 黄色字 \033[0m”
echo -e “\033[34m 蓝色字 \033[0m”
echo -e “\033[35m 紫色字 \033[0m”
echo -e “\033[36m 天蓝字 \033[0m”
echo -e “\033[37m 白色字 \033[0m”
字体底色设置
# 字体底色设置
echo -e “\033[40;37m 黑底白字 \033[0m”
echo -e “\033[41;37m 红底白字 \033[0m”
echo -e “\033[42;37m 绿底白字 \033[0m”
echo -e “\033[43;37m 黄底白字 \033[0m”
echo -e “\033[44;37m 蓝底白字 \033[0m”
echo -e “\033[45;37m 紫底白字 \033[0m”
echo -e “\033[46;37m 天蓝底白字 \033[0m”
echo -e “\033[47;30m 白底黑字 \033[0m”
特殊参数
# 参数
$# 参数的个数
$? shell 脚本运行返回值,OK返回0
$* 所有的参数
$UID 用户id,root的uid=0
$PWD 当前文件夹绝对路径
逻辑运算符解析
# 逻辑运算符解析
-f 判断文件是否存在
-d 判断目录是否存在
-eq 等于,应用于整型数值比较
-ne 不等于,应用于整型数值比较
-lt 小于,应用于整型数值比较
-gt 大于,应用于整型数值比较
-le 小于或等于,应用于整型数值比较
-ge 大于或等于,应用于整型数值比较
-a 双方都成立(and) condition1 -a condition2
-o 单方成立(or) condition1 -o condition2
-z 空字符串
测试脚本编写是否正确
/bin/bash -n if.sh # 如果没有输出任何东西表示脚本编写正确
文件IO
# 将结果写入文件,结果不会在控制台展示,而是在文件中,覆盖写
$ echo result > file
# 将结果写入文件,结果不会在控制台展示,而是在文件中,追加写
$ echo result >> file
echo input < file #获取输入流
一些练习的小例子
-
自动备份mysql数据库
#!/bin/bash # auto backup mysql db # by author nulijiushimeili 2015 # define backup path bak_dir=/opt/datas/mysql_backup/`date +%Y%m%d` mysql_db=sqoop mysql_user=root mysql_pwd=123456 mysql_cmd=/usr/bin/mysqldump if [ $UID -ne 0 ] then echo "Must to be use root for exec shell." exit fi if [ ! -d $bak_dir ] then mkdir -p $bak_dir echo -e "\033[32mThe $bak_dir create successfully!\033[0m" else echo "This $bak_dir is exists ..." fi # mysql backup cmd. mysqldump -u$mysql_user -p$mysql_pwd -d $mysql_db >$bak_dir/$mysql_db.sh if [ $? -eq 0 ] then echo -e "\033[32mThe mysql backup $mysql_db successfully!\033[0m" else echo -e "\033[32mThe mysql backup $mysql_db failed, please check.\033[0m" fi
-
玩具程序: 设置环境变量(第一版)
#!/bin/bash # set env # by author nulijiushimeili 2017 time=`date +%Y%m%d%H%M%S` new_profile="profile_$time" echo $new_profile if [ $UID -ne 0 ] then echo "Must to be use root to exec shell." exit fi if [ $1 == "help" ] then echo "Usage: set-env.sh JAVE_HOME." echo "Usage: set-env.sh help for help." exit fi echo "Are you sure to append this dir to envirement virable?" echo "input y to continue and copy /etc/profile to $new_profile, the new file will as a backup for /etc/profile, if you want to use the old profile, you can rename the histry profile to 'profile'." echo "continue to input 'y', and input 'n' for exit.[y|n]?" read create_file_yes_or_no if [ $create_file_yes_or_no == "y" ] then sudo cp /etc/profile /etc/$new_profile if [ $? -eq 0 ] then echo "create new profile success." if [ $# -gt 0 ] then # content=echo "# $1%nexport $1=$PWD%nexport PATH=\$PATH=\$PATH:\$$1/bin" sh="export PATH=\$PATH:\$$1/bin" home="export $1=$PWD" annotation="# $1" echo "append env variable to profile..." echo "the variable is :" echo "$annotation" echo "$home" echo "$sh" echo "It is appending now,please comfirm agagin:" echo "continue to input 'y', and input 'n' for exit.[y|n]?" read get_yes_or_no if [ $get_yes_or_no == "y" ] then sudo sed -i "4i\ \n" /etc/profile sudo sed -i "4i\\$sh" /etc/profile sudo sed -i "4i\\$home" /etc/profile sudo sed -i "4i\\$annotation" /etc/profile sudo source /etc/profile echo "$1 envirement virable was setted successfully!" echo "$1" else echo "exit!" exit fi else echo "Usage: set-env.sh JAVE_HOME." echo "Usage: set-env.sh help for help." exit fi else echo "create new profile failed. please to check ..." fi else echo "exit!" exit fi
-
3. 玩具程序: 设置环境变量(第二版)
```shell
#!/bin/babin
# set env
# by author nulijiubinimeili 2017
time=`date +%Y%m%d%H%M%S`
new_profile="profile_$time"
echo "will create new profile $new_profile for backup."
# check user, must be root
if [ $UID -ne 0 ]
then
echo "Must to be use root to exec shell."
exit
fi
# help info
if [ $1 == "help" ]
then
echo "Usage: set-env.bin JAVE_HOME.(requer: this binell must in the java home directory.)"
echo "Usage: set-env.bin /opt/modules/jdk1.8.0_161 JAVE_HOME"
echo "Usage: set-env.bin help"
exit
fi
echo "Appending this dir to envirement virable."
echo "input y to continue and copy /etc/profile to $new_profile, the new file will as a backup for /etc/profile, if you want to use the old profile, you can rename the histry profile to 'profile'."
echo "continue to input 'y', and input 'n' for exit.[y|n]?"
read create_file_yes_or_no
if [ $create_file_yes_or_no == "y" ]
then
sudo cp /etc/profile /etc/$new_profile
if [ $? -eq 0 ]
then
echo "create new profile success."
if [ $# -eq 1 ]
then
# Must contains a bin directory in current path.
if [ ! -d $PWD/bin ]
then
echo -e "\033[32mWithout 'bin' directory in current path,pleash check.\033[0m"
exit
fi
# content=echo "# $1%nexport $1=$PWD%nexport PATH=\$PATH:\$$1/bin"
echo "Recommend: set-env.x.x.x.sh /path XXX_HOME"
bin="export PATH=\$PATH:\$$1/bin"
home="export $1=$PWD"
annotation="# $1"
echo "append env variable to profile..."
echo "the variable is :"
echo -e "\033[32m$annotation\033[0m"
echo -e "\033[32m$home\033[0m"
echo -e "\033[32m$bin\033[0m"
echo "It is appending now,please comfirm agagin:"
echo "continue to input 'y', and input 'n' for exit.[y|n]?"
read get_yes_or_no
if [ $get_yes_or_no == "y" ]
then
sudo sed -i "4i\ \n" /etc/profile
sudo sed -i "4i\\$bin" /etc/profile
sudo sed -i "4i\\$home" /etc/profile
sudo sed -i "4i\\$annotation" /etc/profile
source /etc/profile
echo "$1 envirement virable was setted successfully!"
echo -e "\033[32mplease exec 'source /etc/profile' by yourself.\033[0m"
else
echo "exit!"
exit
fi
elif [ $# == 2 ]
then
# content=echo "# $2%nexport $2=$PWD%nexport PATH=\$PATH:\$$2/bin"
bin="export PATH=\$PATH:\$$2/bin"
home="export $2=$1"
annotation="# $2"
echo "append env variable to profile..."
echo "the variable is :"
echo -e "\033[32m$annotation\033[0m"
echo -e "\033[32m$home\033[0m"
echo -e "\033[32m$bin\033[0m"
echo "It is appending now,please comfirm agagin:"
echo "continue to input 'y', and input 'n' for exit.[y|n]?"
read get_yes_or_no
if [ $get_yes_or_no == "y" ]
then
sudo sed -i "4i\\$bin" /etc/profile
sudo sed -i "4i\\$home" /etc/profile
sudo sed -i "4i\\$annotation" /etc/profile
sudo sed -i "4i\ \n" /etc/profile
source /etc/profile
echo "$1 envirement virable was setted successfully!"
echo -e "\033[32mplease exec 'source /etc/profile' by yourself.\033[0m"
else
echo "exit!"
exit
fi
else
echo "Usage: set-env.bin JAVE_HOME.(requer: this binell must in the java home directory.)"
echo "Usage: set-env.bin /opt/modules/jdk1.8.0_161 JAVE_HOME"
echo "Usage: set-env.bin help"
exit
fi
else
echo "create new profile failed. please to check ..."
fi
else
echo "exit!"
exit
fi
```
4. git 提交
```shell
#!/bin/bash
# git commit project
# by author nulijiushimeili
echo "start running shell"
git add .
if (($#>0));
then
git commit -m $1
else
echo "Usage: gitcommit.sh param1"
fi
git push orgin master
if (($?==0))
then
echo "commit success."
else
echo "commit failed, please try to again."
fi
```
5. 启动Tomcat
```shell
#!/bin/bash
# 启动Tomcat
tomPath=/usr/local/soft/tom7
# sh ${tomPath}/bin/shutdown.sh
# 作为参数返回 查找的进程ID
id=`ps -ef |grep tomcat |grep -v 'auto tomcat'|awk '{print $2}'`
kill -9 $id
rm -rf /usr/local/soft/tom7/webapps/ROOT*
cp /home/grq/data/ROOT.war /usr/local/soft/tom7/webapps/
sh ${tomPath}/bin/startup.sh
# 作为参数返回 查找的进程ID
id=$(ps -ef |grep tomcat |grep -v 'auto tomcat'|awk '{print $2}')
```