Linux查看在线用户使用w命令。

declare命令

在上一篇文章Shell基础-变量中我们说道Linux中默认的变量类型是字符串.

我们使用该命令结合+或者-设定或者取消变量类型:

1
$ declare [+|-] [options] 变量名

其中-是设置类型,+是取消设置类型.

常见的数据类型:

  • -a:数组型
  • -i:整型
  • -x:环境变量(其实export命令就是调用的declare -x命令)
  • -r:只读变量(不能改变,不能修改,不能删除,甚至不能取消只读属性)
  • -p:显式声明变量被声明的类型

请看下面的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$ a=1
$ b=2
$ c=$a+$b
$ echo $c # '1+2',because default is string
$
$ declare -i c=$a+$b
$ echo $c # 3

# 定义数组
$ sutdents[0] = 'Kissy'
$ sutdents[1] = 'Tom'
$ declare -a sutdents[2] = 'Kenvin'
# 查看数组
$ echo ${students} # 输出数组手元素
$ echo ${students[2]}
$ echo ${students[*]} # 所有元素

数值运算方法

在上面的例子中我们为了实现ab相加为数值类型,使用declare命令声明了c,其实我们还有更优雅的方法:

1
2
3
$ a=1
$ b=2
$ c=$(expr $a + $b) # 注意:+号的左右两侧必须有空格

除此之外还有一种比较优雅的方式:

1
2
3
4
$ a=1
$ b=2
$ c=$(($a+$b)) # 推荐使用
$ d=$[$a+$b]