Equivalent of __FILE__ and __LINE__ in Bash

后端 未结 4 779

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:

<
4条回答
  •  余生分开走
    2020-12-24 06:03

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

提交回复
热议问题