zl程序教程

您现在的位置是:首页 >  后端

当前栏目

高级变量

变量 高级
2023-06-13 09:15:42 时间
9.1 高级变量赋值

高级变量插图

范例:

[root@centos8 ~]#title=ceo

[root@centos8 ~]#name={title-mage}

[root@centos8 ~]#echoname

[root@centos8 ~]#title=

[root@centos8 ~]#name={title-mage}

[root@centos8 ~]#echoname

[root@centos8 ~]#unset title

[root@centos8 ~]#name={title-mage}

[root@centos8 ~]#echoname

mage

范例:

[root@centos8 ~]#title=ceo

[root@centos8 ~]#name={title:-mage}

[root@centos8 ~]#echoname

[root@centos8 ~]#title=

[root@centos8 ~]#name={title:-mage}

[root@centos8 ~]#echoname

[root@centos8 ~]#unset title

[root@centos8 ~]#name={title:-mage}

[root@centos8 ~]#echoname

mage
9.2 高级变量用法-有类型变量

Shell变量一般是无类型的,但是bash Shell提供了declare和typeset两个命令用于指定变量的类型,两个命令是等价的

declare [选项] 变量名

-r 声明或显示只读变量 -i 将变量定义为整型数 -a 将变量定义为数组 -A 将变量定义为关联数组 -f 显示已定义的所有函数名及其内容 -F 仅显示已定义的所有函数名 -x 声明或显示环境变量和函数,相当于export -l 声明变量为小写字母 declare –l var=UPPER -u 声明变量为大写字母 declare –u var=lower

9.3 变量间接引用 9.3.1 eval命令

eval命令将会首先扫描命令行进行所有的置换,然后再执行该命令。该命令适用于那些一次扫描无法实现其功能的变量,该命令对变量进行两次扫描

范例:

[root@centos8 ~]# CMD=whoami

[root@centos8 ~]# echo CMD

whoami

[root@centos8 ~]# evalCMD

root 

[root@centos8 ~]# n=10 

[root@centos8 ~]# echo {0..n} 

{0..10}

[root@centos8 ~]# eval echo {0..n}

0 1 2 3 4 5 6 7 8 9 10

[root@centos8 ~]#i=1

[root@centos8 ~]#j=a

[root@centos8 ~]#ji=hello

-bash: a1=hello: command not found

[root@centos8 ~]#eval ji=hello

[root@centos8 ~]#echo ji

a1
9.3.2 间接变量引用

如果第一个变量的值是第二个变量的名字,从第一个变量引用第二个变量的值就称为间接变量引用 variable1的值是variable2,而variable2又是变量名,variable2的值为value,间接变量引用是指通过variable1获得变量值value的行为

variable1=variable2

variable2=value

bash Shell提供了两种格式实现间接变量引用

eval tempvar=/$variable1

tempvar={!variable1}

范例:



9.3.3 变量引用reference

[root@centos8 ~]#cat test.sh

#!/bin/bash

ceo=mage

title=ceo

declare -n ref=title

[ -R ref ] echo reference echoref

ceo=wang

echo $ref

[root@centos8 ~]#bash test.sh

reference

wang

本文链接:http://www.yunweipai.com/34354.html

原创文章,作者:kepupublish,如若转载,请注明出处:https://blog.ytso.com/52555.html

centosshell