Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of __FILE__ and __LINE__ in Bash

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" 
like image 663
user368507 Avatar asked Jun 16 '10 17:06

user368507


People also ask

What is << EOF in bash?

This operator stands for the end of the file. This means that wherever a compiler or an interpreter encounters this operator, it will receive an indication that the file it was reading has ended. Similarly, in bash, the EOF operator is used to specify the end of the file.

How can I get the source directory of a bash script?

You can use $BASH_SOURCE : #!/usr/bin/env bash scriptdir="$( dirname -- "$BASH_SOURCE"; )"; Note that you need to use #!/bin/bash and not #!/bin/sh since it's a Bash extension.

What is Dash D in bash?

-d is a operator to test if the given directory exists or not. For example, I am having a only directory called /home/sureshkumar/test/. The directory variable contains the "/home/sureshkumar/test/" if [ -d $directory ]

What is cat << EOT >>?

use cat << EOT >> to insert actual strings and escape logic.


2 Answers

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

like image 108
ezpz Avatar answered Sep 27 '22 02:09

ezpz


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 
like image 24
Kevin Little Avatar answered Sep 25 '22 02:09

Kevin Little