shell 自定义变量

2016-10-08

shell 自定义变量

  简单的脚本:

[root@133 ~]# vim variable.sh

#!/bin/bash

##In this script we will use variables.

d=`date +%H:%M:%S`

echo "The script begin at $d."

echo "Now we'll sleep 2 seconds."

sleep 2

d1=`date +%H:%M:%S`

echo "The script end at $d1."

  脚本中使用到了反引号,d 和 d1 再脚本中作为变量出现。定义变量的格式为:变量名 = 变量的值,当在脚本中引用变量时需要加上 $ 符号。执行结果:

[root@133 ~]# sh variable.sh

The script begin at 16:06:44.

Now we'll sleep 2 seconds.

The script end at 16:06:46.

  数学运算:

  在 shell 中也需要用到数学运算的,下面示例计算两个数字的和。

[root@133 ~]# vim sum.sh

#!/bin/bash

##For get the sum of two numbers.

a=1

b=2

sum=$[$a+$b]

echo "$a+$b=$sum"

  数学计算要用“[ ]”括起来并且外部加一个 $ ,执行结果:

[root@133 ~]# sh sum.sh

1+2=3

  再列举几个例子:

  乘法运算:

[root@133 ~]# a=3;b=2

[root@133 ~]# c=$[$a*$b];echo $c

6

[root@133 ~]# echo "$a x $b=$c"

3 x 2=6

  除法运算:

[root@133 ~]# a=10;b=3

[root@133 ~]# c=$[$a/$b];echo $c

3

  上例中,c 的结果为 3,并不是我们想象的一个小数,这是因为 shell 默认是不支持小数的。如果需要小数得安装 bc 包,bc 工具是 Linux 系统里面的计算器,使用 yum install -y bc 安装。

  如果要想保留小数点,这样来实现:

[root@133 ~]# echo "scale=2;10/3"|bc

3.33

[root@133 ~]# echo "scale=5;10/3"|bc

3.33333

  和用户交互:

  shell 脚本可以实现,让用户输入一些字符串或者让用户去选择的行为。

[root@133 ~]# vim read.sh

#!/bin/bash

##Using 'read' in shell script.

read -p "Please input a number:" x

read -p "Please input another number:" y

sum=$[$x+$y]

echo "The sum of the two numbers is:$sum"

  read 命令就是用在这样的地方,用于和用户交互。它把用户输入的字符串作为变量值。脚本执行过程:

[root@133 ~]# sh read.sh

Please input a number:3

Please input another number:5

The sum of the two numbers is:8

  加入 -x 选项看看执行过程:

[root@133 ~]# sh -x read.sh

+ read -p 'Please input a number:' x

Please input a number:4

+ read -p 'Please input another number:' y

Please input another number:6

+ sum=10

+ echo 'The sum of the two numbers is:10'

The sum of the two numbers is:10

  shell 脚本预设变量

  有时候我们会用到这样的命令 /etc/init.d/iptables restart ,前面的 /etc/init.d/iptables 文件其实是一个 shell 脚本,为什么后面可以跟一个 restart ?这就涉及到了 shell 脚本的预设变量。实际上,shell 脚本在执行的时候后边是可以跟参数的,而且还可以跟多个。

[root@133 ~]# vim option.sh

#!/bin/bash

sum=$[$1+$2]

echo "sum=$sum"

[root@133 ~]# sh -x option.sh 1 2

+ sum=3

+ echo sum=3

sum=3

  在脚本中,$1 和 $2 就是 shell 脚本的预设变量,其中 $1 的值就是在执行的时候输入的 1,而 $2 的值就是执行的时候输入的 2,当然一个脚本的预设变量是没有限制的。另外,还有一个 $0,不管它代表的是脚本本身的名字。改一下脚本:

[root@133 ~]# vim option.sh

#!/bin/bash

echo "$1 $2 $0"

  执行结果:

[root@133 ~]# sh option.sh 1 2

1 2 option.sh

标题:shell 自定义变量
作者:散宜生
地址:https://17kblog.com/articles/2016/10/08/1475922855856.html