views:

57

answers:

4

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"

Thank you

+2  A: 

The variable $0 will give you the name of the executing shell script in bash.

Amardeep
+2  A: 
#!/bin/bash

echo $LINENO
echo `basename $0`

$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.

UPDATE:

#!/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.

ezpz
`basename $0` (no `echo` is necessary)
Dennis Williamson
+2  A: 

You just need to

echo $LINENO
echo $(basename $0)
Loxley
`basename $0` (no `echo` is necessary)
Dennis Williamson
A: 

I find the "BASH_SOURCE" and "BASH_LINENO" built-in arrays very useful:

$ cat xx
#!/bin/bash

_ERR_HDR_FMT="%.23s %s[%s]: "
_ERR_MSG_FMT="${_ERR_HDR_FMT}%s\n"

error_msg()
{
printf "$_ERR_MSG_FMT" $(date +%F.%T.%N) ${BASH_SOURCE[1]##*/} ${BASH_LINENO[0]} "${@}"
}

error_msg "here"


error_msg "and here"

Invoking xx yields

2010-06-16.15:33:13.069 xx[11]: here
2010-06-16.15:33:13.073 xx[14]: and here
Kevin Little