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

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

分享题目:Shell基础-变量、判断、循环
链接URL:https://www.cdcxhl.com/article14/pgoege.html

成都网站建设公司_创新互联,为您提供网站设计定制开发网站建设云服务器外贸网站建设商城网站

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

绵阳服务器托管