shell脚本

本文介绍了如何使用vi编辑器编写Shell脚本,并设置了脚本执行权限。详细讲解了Shell脚本中的变量类型,包括本地变量、环境变量及位置变量等。此外还提供了if...else、case、for循环等控制结构的示例。

一、怎么写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

 

转载于:https://www.cnblogs.com/ng1991/p/8378732.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值