码迷,mamicode.com
首页 > 系统相关 > 详细

shell编程之变量详解

时间:2016-08-14 02:06:21      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:特殊变量

bash中的变量的种类

     1.本地变量 : 生效范围为当前shell进程;对当前shell之外的其他shell进程,包括当前shell的子shell进程均无效

变量赋值: name=‘value‘

          使用引用value:

(1) 直接写字符 name="root"

  (2)变量引用 name="$USER" 

(3)命令引用 name=`command`,name=$()

变量引用: ${name},$name

          显示已定义的所有变量: set 

删除变量: unset name

     2.环境变量 : 生效范围为当前shell进程及其子进程fFs

变量声明,赋值:

export name ="value"

declare -x name="value"

  变量引用: $name , ${name}

显示所有环境变量:

export

      env

      printenv    

删除: unset name

     3.局部变量 : 生效范围为当前shell进程中的代码片段(通常指函数)

     4.位置变量 : $1,$2,...来表示,用于让脚本代码中调用通过命令行传递给它的参数

     5.特殊变量: 

$? 上一次退出程序的退出值

$0 : 执行的脚本的文件名

$* : 代表""$1c$2c$3c$4"",其中c为分隔字符,默认为空格键,代表$1 $2 $3 $4

          $@ : 代表"$1" ,"$2 ","$3" ,"$4" 之意,每个变量都是独立的,一般记忆$@

$*和$@在被双引号包起来的时候才会有差异

  在双引号引起来的情况:

$*: 将所有的参数认为是一个字段

$@: 所有的参数每个都是独立的字段

在没有双引号的情况下$*和$@是一样的


示例:判断给出文件的行数

 linecount="$(wc -l |$1 |cut -d " " -f1)"

echo "$1 has $linecount lines"

实例: 

写一个脚本测试$*和$@显示结果的个数

1.$*和$@带引号

#!/bin/bash
test() {
echo "$#"
}
echo ‘the number of parameter in "$@" is ‘$(test "$@")
echo ‘the number of parameter in "$*" is ‘$(test "$*")

运行结果

[zhang@centos7 shells]$ bash 2.sh  a b c d
the number of parameter in "$@" is 4
the number of parameter in "$*" is 1

2..$*和$@不带引号

#!/bin/bash
test() {
echo "$#"
}
echo ‘the number of parameter in "$@" is ‘$(test $@)
echo ‘the number of parameter in "$*" is ‘$(test $*)

运行结果

[zhang@centos7 shells]$ bash 2.sh  a b c d
the number of parameter in "$@" is 4
the number of parameter in "$*" is 4

由测试结果可以看出带引号的$*输出结果是一个字段而带引号的$@输出的参数每个都是独立的字段


本文出自 “zhang1003995416” 博客,谢绝转载!

shell编程之变量详解

标签:特殊变量

原文地址:http://1003995416.blog.51cto.com/10482168/1837649

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!