您的位置:首页 > 运维架构 > Shell

Shell基础- 变量、判断、循环

2016-12-11 16:02 501 查看
1、shell的基本格式、变量
# shell脚本中要加上解释器 #! /bin/bash

# 用脚本打印出hello world
#! /bin/bash

echo "hello world"
exit

参数:参数是一个存储实数值的实体,脚本中一般被引用

#利用变量回显hello world,下面例子会回显两个hello world。
#! /bin/bash
a="hello world"
echo $a
echo "hello world"
exit

如果参数后面加着其它内容,需要用{}
#! /bin/bash

a="hello world"
echo ${a},i am coming
exit
回显结果:




#计算字符串长度,hello world 连空格,总共11




2、脚本退出
#一个执行成功的脚本返回值为0,不成功为非0
[root@localhost script]# clear
[root@localhost script]# sh hello.sh
hello world,i am coming
11
[root@localhost script]# echo $?
0
#判断一个目录内是否有某个文件,有则回显file exsit ,没有则返回1

[root@localhost script]# cat test.sh
#! /bin/bash
cd /home
if [ -f file ];then
echo "file exsit"
else
exit 2
fi
[root@localhost script]# sh test.sh
[root@localhost script]# echo $?
2
[root@localhost script]#

3、Test语句、if语句

test -d xx 目录是否存在
test -f xx 文件是否存在
test -b xx 是否为块文件
test -x xx 是否为可执行文件
A -eq B 判断是否相等
A -ne B 判断不相等
A -le B 小于等于
A -lt B 小于
A -gt B 大于

#if条件判断语句
if [];then
......
else
......
fi

#if语句嵌套
if [];then
.......
elif [];then

.......
elif [];then
.......
else
......
fi
#test举例,判断test文件是否存在,如果存在对其进行备份操作。如果不在回显信息



#例子:输入一个数值判断其在哪个区间。小于80,大于100,位于80到100之间,用的是if嵌套!
[root@localhost script]# cat if.sh
#! /bin/bash

read -p "plz input a $num:" num

if [ $num -le 80 ];then
echo "num is less 80"
elif [ $num -ge 80 ] && [ $num -le 100 ];then
echo "num between 80 and 100"
else
echo "num is greater than 100"
fi




4、循环语句 for、while

for var in $var1 $var2 $var3 var4... $var
do
......

......

done

#例子:打印1到10数字
[root@localhost home]# cat for1.sh
#! /bin/bash

for var in {1..10}
do
echo "$var"
sleep 2
done
[root@localhost home]# sh for1.sh
1
2
3
4
5
6
7
8
9
10
[root@localhost home]#

#打印方块内容 for嵌套
[root@localhost home]# sh for2.sh
*********
*********
*********
*********
*********
*********
*********
*********
*********
[root@localhost home]# cat for2.sh
#! /bin/bash

for ((i=1;i<10;i++))
do
for ((j=1;j<10;j++))
do
echo -n "*"
done
echo ""
done

# while循环,主要也是用于循环,另外还有continue(跳出continue下面语句,回归顶部命令行)、break(停止、退出循环)

#while语句

while [条件判断]
do
......
......
done

#例子:根据条件判断的,输出1-10
[root@localhost script]# cat while.sh
#! /bin/bash

var=1

while [ $var -le 10 ]
do
echo $var
var=$[$var+1]
done
[root@localhost script]# sh while.sh
1
2
3
4
5
6
7
8
9
10
[root@localhost script]# echo $?
0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  字符串 hello world