linux中Bash内部变量使用示例
$@
“$@”把所有的命令行参数作为一个数组返回。与”$*”不一样,它是作为一个字符串来返回。
“$@”可以通过循环来遍历所有元素,如下脚本:
#!/bin/bash
for var in "$*"; do
echo $var
done
因为$*只把参数作为一个字符串返回,echo就只被调用一次:
~> $ ./testscript.sh firstarg secondarg thirdarg
firstarg secondarg thirdarg
使用$@时:
#!/bin/bash
for var in "$@"; do
echo $var
done
以数组返回所有参数,使用你能够单独地访问每一个参数:
~> $ ./testscript.sh firstarg secondarg thirdarg
firstarg
secondarg
thirdarg
$#
获取命令行参数个数,键入:
#!/bin/bash
echo "$#"
如带3个参数运行脚本,输出如下:
~> $ ./testscript.sh firstarg secondarg thirdarg
3
$!
返回上一个程序执行的进程ID:
~> $ ls &
testfile1 testfile2
[1]+ Done ls
~> $ echo $!
21715
$$
当前进程的pid,如果在bash命令行下执行,相当于是bash进程的pid:
~> $ echo $$
13246
$*
以单个字符串返回所有命令行参数。
testscript.sh:
#!/bin/bash
echo "$*"
带几个参数运行脚本:
./testscript.sh firstarg secondarg thirdarg
输出:
firstarg secondarg thirdarg
$?
返回上一次函数或命令执行的退出状态。通过0表示执行成功,其它的则表示执行失败:
~> $ ls *.blah;echo $?
ls: cannot access *.blah: No such file or directory
2
~> $ ls;echo $?
testfile1 testfile2
0
$1 $2 $3等
从命令行传递给脚本或者一个函数的位置参数:
#!/bin/bash
# $n is the n'th positional parameter
echo "$1"
echo "$2"
echo "$3"
输出如下:
~> $ ./testscript.sh firstarg secondarg thirdarg
firstarg
secondarg
thirdarg
如果位置参数的数量大于9,需要使用大括号:
# "set -- " sets positional parameters
set -- 1 2 3 4 5 6 7 8 nine ten eleven twelfe
echo $10 # outputs 1
echo ${10} # outputs ten
$FUNCNAME
获取当前函数的名称:
my_function()
{
echo "This function is $FUNCNAME" # This will output "This function is my_function"
}
如果在函数外打印此变量:
my_function
echo "This function is $FUNCNAME" # This will output "This function is"
$HOME
用户的主目录
~> $ echo $HOME
/home/user
$IFS
此变量包含用于循环中bash拆分字符串的内部字段分隔符。默认是空白字符\n(newline),\t(tab)或者空格。更改它的话使你能够使用不同分隔符拆分字符串:
IFS=","
INPUTSTR="a,b,c,d"
for field in ${INPUTSTR}; do
echo $field
done
输出:
a
b
c
d
$PWD
输出当前工作目录
~> $ echo $PWD
/home/user
~> $ cd directory
directory> $ echo $PWD
/home/user/directory
$HOSTNAME
系统启动时分配的主机名
~> $ echo $HOSTNAME
mybox.mydomain.com
$LINENO
输出脚本的当前行号。在调试脚本时可能会用到。
#!/bin/bash
# this is line 2
echo something # this is line 3
echo $LINENO # Will output 4