shell脚本(2)

现在知道shell是干什么的?并体验了一下后,现在来看看shell的构成,好比java的构成

1.变量

shell脚本中的变量可以是一个数值、一个命令或者一个路径。定义变量的格式为:变量名=变量的值,在脚本中引用变量时需要加上符号$

下面这个例子将加入变量

  #!/bin/bash
## In this script we will use variables.
## Writen by homey 2019-11-13

    d=`date +%H:%M:%S`				#反引号的作用是将引号内的字符串当成shell命令执行,返回命令的执行结果
    echo "The script begin at $d." #引用变量前面要加$
    echo "Now we'll sleep 2 seconds."
    sleep 2 #睡2秒再执行下面
    d1=`date +%H:%M:%S`
    echo "The script end at $d1."

自己跑一次看看。

2.数字运算

下面这个例子将加入运算

#! /bin/bash 
## For get the sum of two numbers.
## Writen by homey 2019-11-13

a=1
b=2
sum=$[$a+$b]  #数学计算要用[]括起来,并且前面要加上符号$。
echo "$a+$b=$sum"

自己跑一次看看

3.和用户交互

#!/bin/bash
## Using 'read' in shell script.
## Writen by homey 2019-11-13

    read -p "Please input a number:" x
    read -p "Please input another number:" y
            sum=$[$x+$y]
    echo "The sum of two numbers is:$sum"

自己跑一次体验一下。

4.shell脚本预设变量

#!/bin/bash
## 测试预设变量
## Writen by homey 2019-11-13

    sum=$[$1+$2]
    echo "sum=$sum"

结果为

cosun@cosun:/usr/local/sbin$ ./test4.sh 5 46
sum=51

$1表示脚本的第一个参数,$2表示脚本的第二个参数,以此类推

一个脚本的预设变量数量是没有限制的,另外还有$0,它表示脚本本身的名字

5.Shell脚本中的逻辑判断

这个shell脚本与我们的java写的还是不一样,请见下面

#!/bin/bash 

read -p "Please input you score: " a
if ((a<60));then
        echo "You didn't pass the exam."
elif ((a>=60)) && ((a<90));then				# elif相对if,再做一次判断
        echo "Good!You passed the exam."
else
        echo "Very good!Your score is very high."
fi

判断数值大小除了可以使用(( ))的形式外,还可以使用[],但不能使用><=这样的符号了,要使用-lt(小于)、-gt(大于)、-le(小于或等于)、-ge(大于或等于)、-eq(等于)、-ne(不等于)。看个人喜好用什么。

除了if还可以用case

#!/bin/bash

read -p "Input a number: " n
a=$[n%2]
case $a in
1)
        echo "The number is odd."				# odd:奇数
        ;;
0)
        echo "The number is even."				# even:偶数
        ;;
*)
        echo "It's not a number!"
esac

case脚本常用于编写系统服务的启动脚本

6.shell里的循环

#!/bin/bash 

for i in `seq 1 5`; do				# seq 1 5 表示从1到5的一个序列
        echo $i
done

或while循环

#!/bin/bash 

a=6
while [ $a -ge 1]
do
        echo $a
        a=$[$a-1]
done

7.shell里函数

#!/bin/bash

function sum()
{
        sum=$[$1+$2]
        echo $sum
}
sum $1 $2				#预设变量$1 $2

大家可以自由发挥,再加入break 或 continue 甚至shell里还有exit

其实就像我们现在的这个JAVA编程语言一样,shell在这里也仅仅只是入门,大家如需要可自行深入。

最后再次感谢:

https://blog.csdn.net/miss1181248983/article/details/81278937

我这里基本都是按照他的博客去实践的。

发布了51 篇原创文章 · 获赞 4 · 访问量 7897

猜你喜欢

转载自blog.csdn.net/u012174809/article/details/103044542