温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-07-30 20:20:39 来源:网络 阅读:3434 作者:X糊涂仙儿 栏目:网络安全

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

回显结果:

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


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

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


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文件是否存在,如果存在对其进行备份操作。如果不在回显信息

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

#例子:输入一个数值判断其在哪个区间。小于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

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



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



向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI