bash-高级编程--位置变量

特殊变量类型

局部变量

这种变量只有代码块或者函数中才可见

如果变量用local 来声明, 那么它就只能够在该变量被声明的代码块中可见. 这个代码块就是局
部"范围". 在一个函数中, 一个局部变量只有在函数代码块中才有意义.

环境变量

这种变量将影响用户接口和shell的行为

通常情况下,每个进程都有自己的"环境",这个环境是由一组变量组成的, 这些变量存有进程可能需要引用的信息。

一个脚本可以通过export传递环境变量给子进程,但是子进程不能传递环境变量给父进程。

位置参数

从命令行传递到脚本的参数:$0, $1, $2, $3 ...

$0就是脚本自身的名字

#! /bin/bash
# 这个脚本用于测试脚本变量
# $0 代表变量本省
echo -e '$0' "= $0"
# 脚本的第一个参数
echo -e '$1' "= $1"
# 第二个参数
echo -e '$2' "= $2"
# 第三个参数
echo -e '$3' "= $3"

运行结果:

andrew@andrew:/work/linux-sys/bash/2.基本/src$ bash bash_name.sh  name s d
$0 = bash_name.sh
$1 = name
$2 = s
$3 = d

bash_name_test.sh

#!/bin/bash
# 作为用例, 调用这个脚本至少需要10个参数, 比如:
# bash bash_name_test.sh 1 2 3 4 5 6 7 8 9 10
MINPARAMS=10

echo

echo "The name of this script is \"$0\"."
# 添加./是表示当前目录
echo "The name of this script is \"`basename $0`\"."
# 去掉路径名, 剩下文件名, (参见'basename')

echo

if [ -n "$1" ]
# 测试变量被引用.
then
  echo "Parameter #1 is $1" # 需要引用才能够转义"#"
fi

if [ -n "$2" ]
then
  echo "Parameter #2 is $2"
fi

if [ -n "$3" ]
then
   echo "Parameter #3 is $3"
fi
 
# ...


if [ -n "${10}" ] # 大于$9的参数必须用{}括起来.
then
  echo "Parameter #10 is ${10}"
fi
 
echo "-----------------------------------"
echo "All the command-line parameters are: "$*""

if [ $# -lt "$MINPARAMS" ]
then
  echo
  echo "This script needs at least $MINPARAMS command-line arguments!"
fi

echo

exit 0

执行结果

andrew@andrew:/work/linux-sys/bash/2.基本/src$ bash ./bash_name_test.sh   1 2 3 4 5 6 7 8 9 0 

The name of this script is "./bash_name_test.sh".
The name of this script is "bash_name_test.sh".

Parameter #1 is 1
Parameter #2 is 2
Parameter #3 is 3
Parameter #10 is 0
-----------------------------------
All the command-line parameters are: 1 2 3 4 5 6 7 8 9 0

有时候脚本中需要在不知道输入 多少参数的情况下,定位到最后一个可以 借助$#实现, $#表示参数的个数的变量

args=$#
# 位置参数的个数.
lastarg=${!args}
# 或:
lastarg=${!#}
#(感谢, Chris Monson.)
# 注意, 不能直接使用 lastarg=${!$#} , 这会产生错误.
shift命令会重新分配位置参数,其实就是把所有的位置参数向左移动一个位置

使用shift将位置参数进行整体的左移

#! /bin/bash
# shift 是将位置参数整体向左移动的命令

# $@是,一个一个打印出命令参数
# $* 与$@达到的效果一样,但是$*是讲位置参数作为一个整体输出的意思

echo "$@"

shift

echo "$@"

shift 

echo "$*"
andrew@andrew:/work/linux-sys/bash/2.基本/src$ bash shift_test.sh 1 2 3 5 6 
1 2 3 5 6
2 3 5 6
3 5 6
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章