文章目录
shell脚本的定义与执行
1、定义以开头:#!/bin/bash(#!用来说明用什么shell解释,否则使用默认shell)
2、单个“#”来注释当前行
3、几种不同的在终端执行shell脚本方式
1、chmod +x test.sh
./test.sh //添加可执行权限后执行
2、bash test.sh //直接指定用bash来解释test.sh
3、.test.sh(source test.sh) //调用默认shell解释test.sh
写得第一个shell脚本
#!/bin/bash
echo “hello world”
shell中的变量
1、自定义变量
定义变量
变量名=变量值 如: num=10 num = 10(错误写法) //等号与变量之间不能有空格
引用变量
$变量名 如:i=$num //把变量num的值付给i
显示变量
方法 echo $num
清除变量
使用unset 命令可以清除变量
把键盘中输入的字符赋值给变量
方法 read string
根据以上知识写得一个shell脚本 name.sh
#!/bin/bash
num=100
echo “please input a name”
read name
echo $num
echo $name
2、环境变量
shell在开始执行时就已经定义了一些和系统的工作环境有关的变量。以下是一些常见的环境变量
HOME:用于保存注册目录的完全路径名
PATH:用于保存用冒号分隔的目录路径名
HOSTNAME:主机名
SHELL:默认的shell命令解析器
LOGNAME:此变量保存登陆名
PWD:当前工作目录的绝对路径名
例子如下:
#!/bin/bash
echo "Current work is $PWD"
echo “the host name is $HOSTNAME”
3、预定义变量
$#:传给shell脚本参数的数量
$*:传给shell脚本参数的内容
$1、$2、······、$9:运行脚本时传递给其的参数,用空格隔开
$?:命令执行后返回的状态
$0:当前执行的进程名
$$:当前进程的进程号
示例脚本
#!/bin/bash
echo "your shell script name is $0"
echo "the params of your input is $*"
echo "the num of your input params is $#"
echo "the params is $1 $2 $3 $4"
ls
echo "the cmd state is $?"
cd /root
echo "the cmd state is $?"
echo "process id is $$"
4、脚本变量的中特殊符号用法
1、””(双引号):包含的变量会被解释
2、‘ ’(单引号):包含的变量会被作为字符串解释
3、``(数字键1前面的反引号):反引号中的内容作为系统命令,并执行其内容,可以替换输出为一个变量。
4、(转义字符):同C语言 \n \t等echo命令需要加 -e转义
5、(命令序列) (小括号):在子shell中完成,不影响当前shell中的变量
6、{ 命令序列 }(大括号,且大括号首尾应有空格):在当前shell中执行,会影响当前变量
示例代码
#!/bin/bash
name=teacher
string1="good moring $name"
string2='good moring $name'
echo "today is `date`"
echo 'today is `date`'
echo -e "this \n is \t a \n test"
(name=student;echo "1 $name")
echo 1:$name
(name=student;echo "1 $name")
echo 2:$name
echo $name
shell的控制语句
1、test命令
用来测试字符串、文件状态和数字
格式:
test condition 或 [condition ](中括号首尾有空格)
测试文件状态的条件表达式
test -e:是否存在
test -d:是否是目录
test -f:是否是文件
test -r:是否可读
test -w:是否可写
test -x:是否可执行
test -L:是否是符号链接
test -c:是否字符设备
test -b:是否是块设备
test -e:文件是否非空
示例:
测试/usr/include是不是目录文件
test -d /usr/include
测试/usr/include/stdio.h是否可写
test -w /usr/include/stdio.h
测试字符串的条件表达式
#变量a为空返回真
[ -z "$a" ]
#变量a不为空返回真
[ -n “$a” ]
#字符串相等返回真
[ “str1” = “str2”]
#字符串不相等返回真
[ “str1” != “str2”]
测试数值格式如下
[ num1 operartor num2 ]
operator可以是
1、-eq 数值相等
2、-ne 数值不相等
3、-gt num1大于num2
4、-ge num1大于等于num2
5、-le num小于等于num2
6、-lt num小于num2
2、控制语句
2.1分支结构
if [ 条件1 ];then
执行第一段程序
else
执行第二段程序
fi
if [ 条件1 ];then
执行第一段程序
elif [ 条件2 ];then
执行第二段程序
else
执行第三段程序
fi
case $变量名称 in
第一个变量内容)
程序段1
;;
第二个变量内容)
程序段2
*)
其他程序段
exit 1
esac
示例代码
#!/bin/bash
echo "input your choice"
read choice
case "$choice" in
y | yes | Yes | YES)
echo "It's right"
;;
*)
exit 1
esac
2.2循环结构
for (初始值;限制值;步长)
do
程序段
done
while [ 当满足条件 ]
do
程序段
done
示例代码
#!/bin/bash
#declare -i s是将变量s当作int型参数运算
declare -i i
declare -i s
while [ "$i" != "101" ]
do
s+=i;
i=i+1;
done
echo "the count is $s"