0

...that is to say, is there a means by which I can read the full command that's being evaluated AS it's happening? Here's a contrived example, but one I feel makes the question clear:

function showOwnEvaluation {
    local evaluatingCommand=????
    [[ "$evaluatingCommand" =~ ^showOwnEvaluation ]] && echo "Original Function"
}

alias sOE='showOwnEvaluation'

$ showOwnEvaluation 123
# Output: Original Function

$ sOE 123
# Output: 

Basically the ability to run echo "$(!-1)" for the current, active command? A echo "$(!0)", if you will?

What I'd like to accomplish here is this: if I'm assigning the result of an expansion to a variable:

someVar=$(myFunc)

...I'd like to be able to alter the response from myFunc based on the name of the variable it's being set to. I simply cannot figure out how to get the someVar= portion of the expression, if, indeed, it's even possible to DO such a thing (without slapping a full emulation over the terminal and monitoring all of the I/O, of course).

I know this may seem like a nonsensical desire, here, but I actually do have a valid use-case. I'm just uncertain if it's even feasible.

2
  • bash -v or bash -x? Commented Jan 26 at 1:12
  • 1
    Early in your script, uou can get the script name from $0 and the $# parameters from $1, $2, ... Commented Jan 26 at 4:35

1 Answer 1

1

The closest feature to what you asked for is probably this:

BASH_COMMAND
The command currently being executed or about to be executed, unless the shell is executing a command as the result of a trap, in which case it is the command executing at the time of the trap. If BASH_COMMAND is unset, it loses its special properties, even if it is subsequently reset.

But this is not what you want. The problem with your approach is that the required information has to be passed across a shell boundary: someVar=$(myFunc) is an assignment in the calling shell but myFunc is executed in a subshell.

You can make the function write into a variable (which is faster anyway...) instead of writing to stdout and having to catch this with a subshell:

function showOwnEvaluation {
        test $# -eq 2 || return 2
        local targetVar="$1" evaluatingCommand="$2"
        local result
        if   [[ "$targetVar" =~ ^showOwnEvaluation ]]; then
                result='Original Function'
        elif [[ "$targetVar" = foo ]]; then
                result='bar'
        else
                result='whatever'
        fi
        if [[ -z "$targetVar" || "$targetVar" = '-' ]]; then
                printf '%s\n' "$result"
        else
                local -n ref="$targetVar"
                ref="$result"
        fi
}

showOwnEvaluation someVar 124
declare -p someVar

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.