shell变量

一.shell 变量
1.变量类型
shell变量是一种很“弱”的变量,默认情况下,一个变量保存一个串,shell不关心这个串是什么含义。所以若要进行数学运算,必须使用一些命令例如let、declare、expr、双括号等。
运行shell时,会同时存在三种变量:
1) 局部变量 局部变量在脚本或命令中定义,仅在当前shell实例中有效,其他shell启动的程序不能访问局部变量。
2) 环境变量 所有的程序,包括shell启动的程序,都能访问环境变量,有些程序需要环境变量来保证其正常运行。必要的时候shell脚本也可以定义环境变量。
3) shell变量 shell变量是由shell程序设置的特殊变量。shell变量中有一部分是环境变量,有一部分是局部变量,这些变量保证了shell的正常运行

2.变量赋值
定义变量时,变量名不加美元符号($,PHP语言中变量需要)

例:

[root@localhost tsh]# vim test.sh
#!/bin/bash
a="beijing"
echo $a

[root@localhost tsh]# chmod +x test.sh
[root@localhost tsh]# ./test.sh 
beijing


注意,变量名和等号之间不能有空格,这可能和你熟悉的所有编程语言都不一样。同时,变量名的命名须遵循如下规则:
1).首个字符必须为字母(a-z,A-Z)。
2).中间不能有空格,可以使用下划线(_)。
3).不能使用标点符号。
4).不能使用bash里的关键字(可用help命令查看保留关键字)。
例:
[root@localhost tsh]# vim test.sh
#!/bin/bash
help

[root@localhost tsh]# chmod +x test.sh
[root@localhost tsh]# ./test.sh 
GNU bash, version 4.3.8(1)-release (x86_64-pc-linux-gnu)
These shell commands are defined internally. Type `help' to see this list.
Type `help name' to find out more about the function `name'.
Use `info bash' to find out more about the shell in general.
Use `man -k' or `info' to find out more about commands not in this list.

A star (*) next to a name means that the command is disabled.

job_spec [&] history [-c] [-d offset] [n] or hist>
(( expression )) if COMMANDS; then COMMANDS; [ elif C>
. filename [arguments] jobs [-lnprs] [jobspec ...] or jobs >
: kill [-s sigspec | -n signum | -sigs>
[ arg... ] let arg [arg ...]
[[ expression ]] local [option] name[=value] ...
alias [-p] [name[=value] ... ] logout [n]
bg [job_spec ...] mapfile [-n count] [-O origin] [-s c>
bind [-lpsvPSVX] [-m keymap] [-f file> popd [-n] [+N | -N]
break [n] printf [-v var] format [arguments]
builtin [shell-builtin [arg ...]] pushd [-n] [+N | -N | dir]
caller [expr] pwd [-LP]
case WORD in [PATTERN [| PATTERN]...)> read [-ers] [-a array] [-d delim] [->
cd [-L|[-P [-e]] [-@]] [dir] readarray [-n count] [-O origin] [-s>
command [-pVv] command [arg ...] readonly [-aAf] [name[=value] ...] o>
compgen [-abcdefgjksuv] [-o option] > return [n]
complete [-abcdefgjksuv] [-pr] [-DE] > select NAME [in WORDS ... ;] do COMM>
compopt [-o|+o option] [-DE] [name ..> set [-abefhkmnptuvxBCHP] [-o option->
continue [n] shift [n]
coproc [NAME] command [redirections] shopt [-pqsu] [-o] [optname ...]
declare [-aAfFgilnrtux] [-p] [name[=v> source filename [arguments]
dirs [-clpv] [+N] [-N] suspend [-f]
disown [-h] [-ar] [jobspec ...] test [expr]
echo [-neE] [arg ...] time [-p] pipeline
enable [-a] [-dnps] [-f filename] [na> times
eval [arg ...] trap [-lp] [[arg] signal_spec ...]
exec [-cl] [-a name] [command [argume> true
exit [n] type [-afptP] name [name ...]
export [-fn] [name[=value] ...] or ex> typeset [-aAfFgilrtux] [-p] name[=va>
false ulimit [-SHabcdefilmnpqrstuvxT] [lim>
fc [-e ename] [-lnr] [first] [last] o> umask [-p] [-S] [mode]
fg [job_spec] unalias [-a] name [name ...]
for NAME [in WORDS ... ] ; do COMMAND> unset [-f] [-v] [-n] [name ...]
for (( exp1; exp2; exp3 )); do COMMAN> until COMMANDS; do COMMANDS; done
function name { COMMANDS ; } or name > variables - Names and meanings of so>
getopts optstring name [arg] wait [-n] [id ...]
hash [-lr] [-p pathname] [-dt] [name > while COMMANDS; do COMMANDS; done
help [-dms] [pattern ...] { COMMANDS ; }

除了显式地直接赋值,还可以用语句给变量赋值,如 将 /home 下目录的文件名循环出来
[root@localhost tsh]# vim test.sh
#! /bin/bash
for name in `ls /home`
do
    echo "The value is: $name"
done

[root@localhost tsh]# chmod +x test.sh
[root@localhost tsh]# ./test.sh 
The value is: HelloWorld.swift
The value is: swift22
将home目录下的文件名逐个赋值给name变量,并且逐个打印出来,上面例子可知home目录下面有两个文件,验证一下是否正确:
[root@localhost tsh]#ls /home
HelloWorld.swift
swift22
没错,和上面shell的运行脚本是一样的结果。

3.使用变量
使用一个定义过的变量,只要在变量名前面加美元符号即可,并且一个定义了的变量可以连续使用,并且第二次赋值的时候变量前面也不需要添加“$”符号,只有在使用(取值)的时候才加,如:
[root@localhost tsh]# vim test.sh
#! /bin/bash
a="beijing"
echo $a
echo ${a}
a=2
echo $a

[root@localhost tsh]# chmod +x test.sh
[root@localhost tsh]# ./test.sh 
beijing
beijing
2
变量名外面的花括号是可选的,加不加都行,加花括号是为了帮助解释器识别变量的边界,例:
[root@localhost tsh]# vim test.sh
#!/bin/bash
for a in 1 2 3 4 5 ; do
    echo "a: ${a}hello"
done
for a in 1 2 3 4 5 ; do
    echo "a: $ahello"
done

[root@localhost tsh]# chmod +x test.sh
[root@localhost tsh]# ./test.sh 
a: 1hello
a: 2hello
a: 3hello
a: 4hello
a: 5hello
a: 
a: 
a: 
a: 
a: 
前一种情况加了花括号,解释器能认出来a是个独立的变量,可以正常输出我们预期的效果,但是后面的for没有a变量加花括号,解释器就会把$ahello当成一个变量(其值为空),代码执行结果就不是我们期望的样子了。
4.只读变量
只读变量顾名思义就是类似于C语言中的常量,只能读取不能再次被赋值,使用 readonly 命令可以将变量定义为只读变量,只读变量的值不能被改变。
例:
[root@localhost tsh]# vim test.sh
#!/bin/bash
a="beijing"
echo $a
readonly a
a="shanghai"
echo $a

[root@localhost tsh]# chmod +x test.sh
[root@localhost tsh]# ./test.sh 
beijing
beijing

可以看到运行结果已经给出了提示,a是只读变量,因此第二个打印并没有按照我们的赋值输出“shanghai”,依然是打印出了“beijing”
5.删除变量
使用 unset 命令可以删除变量。语法:
unset variable_name
变量被删除后不能再次使用。unset 命令不能删除只读变量。
例:
[root@localhost tsh]# vim test.sh
#!/bin/sh
a="beijing"
echo $a
unset a
echo $a

b="shanghai"
readonly b
echo $b
unset b
echo $b

[root@localhost tsh]# chmod +x test.sh
[root@localhost tsh]# ./test.sh 
beijing

shanghai
shanghai

可以看到运行结果第二个echo $a只有一行空行输出,说明此时a变量已经没有了,对于b已经设置了只读属性,因此两个都能正确输出,并且执行结果给出提示不能删除变量b,因为b是只读变量。

二.Shell 字符串
字符串是shell编程中最常用最有用的数据类型(除了数字和字符串,也没啥其它类型好用了),字符串可以用单引号,也可以用双引号,也可以不用引号。单双引号的区别跟PHP类似。
1.单引号
1).单引号里的任何字符都会原样输出,单引号字符串中的变量是无效的;
2).单引号字串中不能出现单引号(对单引号使用转义符后也不行)。
例:
[root@localhost tsh]# vim test.sh
#!/bin/sh
a='beijing'
echo $a
b="shanghai"
echo 'hello ${b} word'

[root@localhost tsh]# chmod +x test.sh
[root@localhost tsh]# ./test.sh 
beijing
hello ${b} word
可以看出,上面单引号里面的字符串是没有任何作用的,此时${b}完全成了字符串里面的一部分。
2.双引号
1).双引号里可以有变量
2).双引号里可以出现转义字符
[root@localhost tsh]# vim test.sh
#!/bin/bash
a='beijing'
str="Hello, \"$a\"! \n"
echo $str
str="Hello, ${a}! \n"
echo $str

[root@localhost tsh]# chmod +x test.sh
[root@localhost tsh]# ./test.sh 
Hello, "beijing"! \n
Hello, beijing! \n

3.拼接字符串
例:
[root@localhost tsh]# vim test.sh
#!/bin/bash
a=" beijing"
b="shanghai"
c="hello, "$a" !"
d="hello, ${b} !"
echo $c $d

[root@localhost tsh]# chmod +x test.sh
[root@localhost tsh]# ./test.sh 
hello, beijing ! hello, shanghai !
4.获取字符串长度
[root@localhost tsh]# vim test.sh
#!/bin/bash
a="1234"
echo "string a len:" ${#a}

[root@localhost tsh]# chmod +x test.sh
[root@localhost tsh]# ./test.sh 
string a len: 4
5.提取子字符串
以下实例从字符串第 2 个字符开始截取 4 个字符:
[root@localhost tsh]# vim test.sh
#!/bin/bash
a="1234567890"
echo "get str is:" ${a:1:4} 

[root@localhost tsh]# chmod +x test.sh
[root@localhost tsh]# ./test.sh 
get str is: 2345
6.查找子字符串
查找字符 "3 或7" 的位置:
[root@localhost tsh]# vim test.sh
#!/bin/bash
a="123qwe4567lkjh0987"
echo "3|7 index is:"`expr index "$a" 37`

[root@localhost tsh]# chmod +x test.sh
[root@localhost tsh]# ./test.sh 
3|7 index is:3

注意: 以上脚本中 "`" 是反引号,而不是单引号 "'",不要看错了哦。

三.Shell 数组
bash支持一维数组(不支持多维数组),并且没有限定数组的大小。类似与C语言,数组元素的下标由0开始编号。获取数组中的元素要利用下标,下标可以是整数或算术表达式,其值应大于或等于0。
1.定义数组
在Shell中,用括号来表示数组,数组元素用"空格"符号分割开。定义数组的一般形式为:
数组名=(值1 值2 ... 值n)
例如:
array_name=(value0 value1 value2 value3)
或者
array_name=(
value0
value1
value2
value3
)
还可以单独定义数组的各个分量:
array_name[0]=value0
array_name[1]=value1
array_name[n]=valuen
可以不使用连续的下标,而且下标的范围没有限制。
2.读取数组
读取数组元素值的一般格式是:
${数组名[下标]}
例:
valuen=${array_name[n]}
使用@符号可以获取数组中的所有元素,例如:
echo ${array_name[@]}
3.获取数组的长度
获取数组长度的方法与获取字符串长度的方法相同,例如:
# 取得数组元素的个数:length=${#array_name[@]},或者length=${#array_name[*]}
# 取得数组单个元素的长度:lengthn=${#array_name[n]}
例:
[root@localhost tsh]# vim test.sh
#!/bin/bash
array=(1 a ab w3e)
echo "数组内容:"${array[@]}
array[0]=2
array[1]='e'
array[2]='cvb'
echo "数组内容:"${array[@]}
echo "数组第二个元素内容:"${array[1]}
count=${#array[*]}
echo "数组长度:"$count
len=${#array[3]}
echo "第四个元素内容长度:"$len

[root@localhost tsh]# chmod +x test.sh
[root@localhost tsh]# ./test.sh 
数组内容:1 a ab w3e
数组内容:2 e cvb w3e
数组第二个元素内容:e
数组长度:4
第四个元素内容长度:3

四.Shell 注释
以"#"开头的行就是注释,会被解释器忽略。
sh里没有多行注释,只能每一行加一个#号。只能像这样:
#--------------------------------------------
# 这是一个注释
# 作者:张三
# 说明:程序功能
#--------------------------------------------
##### 用户配置区 开始 #####
#
#
# 这里可以添加脚本描述信息
#
#
##### 用户配置区 结束 #####
如果在开发过程中,遇到大段的代码需要临时注释起来,过一会儿又取消注释,怎么办呢?
每一行加个#符号太费力了,可以把这一段要注释的代码用一对花括号括起来,定义成一个函数,没有地方调用这个函数,这块代码就不会执行,达到了和注释一样的效果。










  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值