shell脚本

一、怎么写shell

利用vi编辑器编辑脚本,将脚本命名为脚本功能.sh
Shell脚本不是复杂的程序,它是按行解释的,脚本第一行总是以#!/bin/sh 开头,它通知系统以下的Shell程序使用系统上的Bourne Shell来解释。
编写脚本要实现的功能
编写完后给脚本添加执行权限:chmod u+x ScripName
运行脚本:ScripName或 ./ScripName

 

二、变量

命名规范:
首个字符必须为字母或者下划线(a-z  A-Z)
变量名和等号之间不能有空格,可以是下划线
不能使用标点符号
不能使用bash里的关键字
查看变量
使用echo 输出用户名。
只读变量
只要在变量名前加readonly

本地变量:用户自定义的变量。

环境变量:用于所有用户变量,用于用户进程前,必须用export命令导出。

位置变量:$0(脚本名),$1-$9:脚本参数。

特定变量:脚本运行时的一些相关信息

 

 

三、控制结构

#!/bin/sh
echo -e "Enter the first integer:\c"
read FIRST
echo -n "Enter the second integer:"
read SECOND
if [ "$FIRST" -gt "$SECOND" ]
then
echo "$FIRST is greater than $SECOND"
elif [ "$FIRST" -gt "$SECOND" ]
then
echo "$FIRST is less than $SECOND"
else
echo "$FIRST is equal to $SECOND"
fi

 

示例
#!/bin/sh
#caseTest
#to test the method of case
USER=`whoami`

case $USER in
root)echo “You can do all the operations”
;;
Dave)echo "You can do some operations”
;;
*)echo "Sorry,you can not do anything"
;;
esac

 

示例
#!/bin/sh
#forTest
#to test the method of for
COUNTER=0
for FILES in *
do
COUNTER=`expr $COUNTER + 1`
done
echo "There are $COUNTER files in `pwd` "

 

格式:until 条件
do
命令
done

 

while 命令
do
命令
done

 

posted @ 2018-01-29 18:10  海东青Lo  阅读(136)  评论(0编辑  收藏  举报