等价于 Bash 中的 __FILE__ 和 __LINE__ [英] Equivalent of __FILE__ and __LINE__ in Bash
本文介绍了等价于 Bash 中的 __FILE__ 和 __LINE__的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
bash 中是否有任何变量包含所执行的 .sh 文件的名称?行号也很好.
Is there any variable in bash that contains the name of the .sh file executed? The line number would be great too.
我想在错误消息中使用它,例如:
I want to use it in error messages such as:
echo "ERROR: [$FILE:L$LINE] $somefile not found"
推荐答案
#!/bin/bash
echo $LINENO
echo `basename $0`
$LINENO
表示当前行号当前文件的 $0
.我使用 basename
来确保您只获取文件名而不是路径.
$LINENO
for the current line number
$0
for the current file. I used basename
to ensure you only get the file name and not the path.
更新:
#!/bin/bash
MY_NAME=`basename $0`
function ouch {
echo "Fail @ [${MY_NAME}:${1}]"
exit 1
}
ouch $LINENO
如果使用函数方法,则必须将该行作为参数传递,否则您将获得函数定义的行.
You have to pass the line as a parameter if you use the function approach else you will get the line of the function definition.
这篇关于等价于 Bash 中的 __FILE__ 和 __LINE__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文