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"
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.
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.
-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 ]
use cat << EOT >> to insert actual strings and escape logic.
#!/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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With