Equivalent of __FILE__ and __LINE__ in Bash

后端 未结 4 769

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条回答
  •  Happy的楠姐
    2020-12-24 06:03

    Here's how to do it in a reusable function. if the following is in a file named script:

    #!/bin/bash
    debug() {
      echo "${BASH_SOURCE[1]##*/}:${FUNCNAME[1]}[${BASH_LINENO[0]}]" > /dev/tty
    }
    debug
    

    This produces the output:

    script:main[5]    
    

    Which indicates the line on which debug was called.


    The following will print out the filename, function, line and an optional message.

    Also works in zsh for extra goodness.

    # Say the file, line number and optional message for debugging
    # Inspired by bash's `caller` builtin
    # Thanks to https://unix.stackexchange.com/a/453153/143394
    function yelp () {
      # shellcheck disable=SC2154  # undeclared zsh variables in bash
      if [[ $BASH_VERSION ]]; then
        local file=${BASH_SOURCE[1]##*/} func=${FUNCNAME[1]} line=${BASH_LINENO[0]}
      else  # zsh
        emulate -L zsh  # because we may be sourced by zsh `emulate bash -c`
        # $funcfiletrace has format:  file:line
        local file=${funcfiletrace[1]%:*} line=${funcfiletrace[1]##*:}
        local func=${funcstack[2]}
        [[ $func =~ / ]] && func=source  # $func may be filename. Use bash behaviour
      fi
      echo "${file##*/}:$func:$line $*" > /dev/tty
    }
    

提交回复
热议问题