知识点
1.用source执行脚本和用bash执行的区别是什么?
答:用source执行的脚本,变量会在父shell下生效,用.也是
用bash执行的脚本,变量不会在父shell下生效
2.如何自定义环境变量
普通变量:变量名=变量值
环境变量:export 变量名=变量值
3.定义变量内容,不加引号、单引号、双引号、反引号结果由什么不同?该怎么用
不加引号:适用于一般场景,不能带空格
单引号:所见即所得
双引号:解析双引号内的变量
反引号:强制命令解析
4.在shell编程中,如果访问变量值,可以变量前加一个$符号
5.下列对shell变量FRUTT操作,正确的是 显示变量的值:echo $FRUTT
练习
1、请使用shell脚本打印下面语句中字符数不小于6的单词
I am giaogg and I like eating and sleeping
第一种方法:
[root@controller shell]# cat 1.sh
#!/bin/bash
str='I am giaogg and I like eating and sleeping'
for i in $str
do
echo $i | xargs -n1 | egrep "^[a-z]{6,}"
done
[root@controller shell]# sh 1.sh
giaogg
eating
sleeping
第二种方法:
[root@controller shell]# vim 2.sh
#!/bin/bash
str='I am giaogg and I like eating and sleeping'
for i in $str
do
[ `echo $i|wc -L` -ge 6 ] && echo $i
done
2、写出shell脚本,通过传参的方式,传入以下内容,并打印下面语句中字符数不小于6的单词
I am giaogg and I like eating and sleeping
#传参方法 $1 $* $@等等
[root@controller shell]# cat 3.sh
#!/bin/bash
for i in $*
do
echo $i | xargs -n1 | egrep "^[a-Z]{6,}"
done
[root@controller shell]# sh 3.sh 'I am giaogg and I like eating and sleeping'
giaogg
eating
sleeping
3、使用脚本传参的方式实现整数的加、减、乘、除、取余、幂运算
[root@controller shell]# vim 4.sh
#!/bin/bash
x=$1
y=$2
echo "$1+$2="`expr $1 + $2`
echo "$1-$2="$[$1-$2]
echo "$1*$2="`echo $1*$2|bc`
echo "$1/$2="`awk -vx=$x -vy=$y 'BEGIN{print x / y}'`
[root@controller shell]# sh 4.sh 2 3
2+3=5
2-3=-1
2*3=6
2/3=0.666667
升级版
[root@controller shell]# cat 5.sh
#!/bin/bash
x=$1
y=$2
if [ $# -ne 2 ];then
echo "Usage:sh $0 参数必须为2个数字 语法错误!"
exit
fi
if [ $1 -gt $2 ];then
echo "数值对比:$1 > $2"
elif [ $1 -eq $2 ];then
echo "数值对比:$1 = $2"
else [ $1 -le $2 ]
echo "数值对比:$1 < $2"
fi
echo "$1+$2="`awk -vx=$x -vy=$y 'BEGIN{print x + y}'`
echo "$1-$2="`awk -vx=$x -vy=$y 'BEGIN{print x - y}'`
echo "$1*$2="`awk -vx=$x -vy=$y 'BEGIN{print x * y}'`
echo "$1/$2="`awk -vx=$x -vy=$y 'BEGIN{print x / y}'`
[root@controller shell]# sh 5.sh 1
Usage:sh 5.sh 参数必须为2个数字 语法错误!
[root@controller shell]# sh 5.sh 1 2 3
Usage:sh 5.sh 参数必须为2个数字 语法错误!
[root@controller shell]# sh 5.sh 1 2
数值对比:1 < 2
1+2=3
1-2=-1
1*2=2
1/2=0.5
4、使用脚本变量传参的三种方式,写一个脚本,通过传参方式修改主机名和IP地址
[root@node3 shell]# cat ip.sh
#!/bin/bash
hostnamectl set-hostname $1
sed -ri "s#^IPADDR=(.*)#IPADDR='$2'#g" /etc/sysconfig/network-scripts/ifcfg-ens32
systemctl restart network