Bash使用示例(2) – 内部变量

$@



“$@”把所有的命令行参数作为一个数组返回。与”$*”不一样,它是作为一个字符串来返回。
“$@”可以通过循环来遍历所有元素,如下脚本:

  1. #!/bin/bash
  2. for var in "$*"; do
  3.     echo $var
  4. done

因为$*只把参数作为一个字符串返回,echo就只被调用一次:

  1. ~> $ ./testscript.sh firstarg secondarg thirdarg
  2. firstarg secondarg thirdarg

使用$@时:

  1. #!/bin/bash
  2. for var in "$@"; do
  3.     echo $var
  4. done

以数组返回所有参数,使用你能够单独地访问每一个参数:

  1. ~> $ ./testscript.sh firstarg secondarg thirdarg
  2. firstarg
  3. secondarg
  4. thirdarg

$#



获取命令行参数个数,键入:

  1. #!/bin/bash
  2. echo "$#"

如带3个参数运行脚本,输出如下:

  1. ~> $ ./testscript.sh firstarg secondarg thirdarg
  2. 3

$!



返回上一个程序执行的进程ID:

  1. ~> $ ls &
  2. testfile1 testfile2
  3. [1]+  Done                    ls
  4. ~> $ echo $!
  5. 21715

$$



当前进程的pid,如果在bash命令行下执行,相当于是bash进程的pid:

  1. ~> $ echo $$
  2. 13246

$*



以单个字符串返回所有命令行参数。
testscript.sh:

  1. #!/bin/bash
  2. echo "$*"

带几个参数运行脚本:

  1. ./testscript.sh firstarg secondarg thirdarg

输出:

  1. firstarg secondarg thirdarg

$?



返回上一次函数或命令执行的退出状态。通过0表示执行成功,其它的则表示执行失败:

  1. ~> $ ls *.blah;echo $?
  2. ls: cannot access *.blah: No such file or directory
  3. 2
  4. ~> $ ls;echo $?
  5. testfile1 testfile2
  6. 0

$1 $2 $3等



从命令行传递给脚本或者一个函数的位置参数:

  1. #!/bin/bash
  2. # $n is the n'th positional parameter
  3. echo "$1"
  4. echo "$2"
  5. echo "$3"

输出如下:
~> $ ./testscript.sh firstarg secondarg thirdarg

  1. firstarg
  2. secondarg
  3. thirdarg

如果位置参数的数量大于9,需要使用大括号:

  1. #  "set -- " sets positional parameters
  2. set -- 1 2 3 4 5 6 7 8 nine ten eleven twelfe
  3. echo $10   # outputs 1
  4. echo ${10} # outputs ten

$FUNCNAME



获取当前函数的名称:

  1. my_function()
  2. {
  3.     echo "This function is $FUNCNAME"    # This will output "This function is my_function"
  4. }

如果在函数外打印此变量:

  1. my_function
  2.  
  3. echo "This function is $FUNCNAME"    # This will output "This function is"

$HOME



用户的主目录

  1. ~> $ echo $HOME
  2. /home/user

$IFS



此变量包含用于循环中bash拆分字符串的内部字段分隔符。默认是空白字符\n(newline),\t(tab)或者空格。更改它的话使你能够使用不同分隔符拆分字符串:

  1. IFS=","
  2. INPUTSTR="a,b,c,d"
  3. for field in ${INPUTSTR}; do
  4.     echo $field
  5. done

输出:
a
b
c
d

$PWD



输出当前工作目录

  1. ~> $ echo $PWD
  2. /home/user
  3. ~> $ cd directory
  4. directory> $ echo $PWD
  5. /home/user/directory

$HOSTNAME



系统启动时分配的主机名

  1. ~> $ echo $HOSTNAME
  2. mybox.mydomain.com

$LINENO



输出脚本的当前行号。在调试脚本时可能会用到。

  1. #!/bin/bash
  2. # this is line 2
  3. echo something  # this is line 3
  4. echo $LINENO # Will output 4
标签:Bash 发布于:2019-11-21 03:07:25