shell 变量

## 引言
shell这门语言,作为与Linux交互效率最高的工具,我相信每个code monkey在工作中或多或少都会用到;我今天要讲的是这门语言中最基本的部分——变量。shell中的变量与类C语言差异较大,相信大家看完后都会有所收获。

语法

在shell中,我们可以使用FOO=BAR这样的方式声明变量(注意,这里不能有空格),当使用这种方式声明变量时,变量是没有类型的,或者说变量的类型可以根据上下文自己转换。比如:


a=2334                   # Integer.
let "a += 1"
echo "a = $a "           # a = 2335
echo                     # Integer, still.


b=${a/23/BB}             # Substitute "BB" for "23".
                         # This transforms $b into a string.
echo "b = $b"            # b = BB35
declare -i b             # Declaring it an integer doesn't help.
echo "b = $b"            # b = BB35

let "b += 1"             # BB35 + 1
echo "b = $b"            # b = 1
echo                     # Bash sets the "integer value" of a string to 0.

c=BB34
echo "c = $c"            # c = BB34
d=${c/BB/23}             # Substitute "23" for "BB".
                         # This makes $d an integer.
echo "d = $d"            # d = 2334
let "d += 1"             # 2334 + 1
echo "d = $d"            # d = 2335

declare

我们可以使用shell内置的declare声明变量:

OptionMeaning
-aVariable is an array.
-fUse function names only.
-iThe variable is to be treated as an integer; arithmetic evaluation is performed when the variable is assigned a value (see Section 3.4.6).
-pDisplay the attributes and values of each variable. When -p is used, additional options are ignored.
-rMake variables read-only. These variables cannot then be assigned values by subsequent assignment statements, nor can they be unset.
-tGive each variable the trace attribute.
-xMark each variable for export to subsequent commands via the environment.

shell支持三种数据类型:字符串、整型、数组。

字符串类型

字符串类型是shell声明一个变量时默认的类型,当我们执行

JAVA_HOME=/usr/default/java

时,JAVA_HOME这个变量的类型是string,

语法

语法说明
${parameter:-defaultValue}Get default shell variables value
${parameter:=defaultValue}Set default shell variables value
${parameter:?”Error Message”}Display an error message if parameter is not set
${#var}Find the length of the string
${var%pattern}Remove from shortest rear (end) pattern
${var%%pattern}Remove from longest rear (end) pattern
${var:num1:num2}Substring
${var#pattern}Remove from shortest front pattern
${var##pattern}Remove from longest front pattern
${var/pattern/string}Find and replace (only replace first occurrence)
${var//pattern/string}Find and replace all occurrences

参考

  1. HowTo: Use Bash Parameter Substitution Like A Pro
  2. Bash Variables Are Untyped
  3. Types of variables
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值