百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>服务器> linux中Bash内部变量使用示例
分享文章到:

linux中Bash内部变量使用示例

发布时间:01/15 来源: 浏览: 关键词:
下面我们来看一篇关于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

打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有10人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板