Home > Net >  How to echo script invocation without variable expansion of its args
How to echo script invocation without variable expansion of its args

Time:10-20

From within a bash script, I'd like to echo script invocation without expanding variables passed as arguments.

Echoing script invocation with expanded variables can be achieved with

echo "${BASH_SOURCE[0]} ${*}"

Echoing (the script's, or any other comand's) history using

echo "$(tail -n 1 ~/.bash_history)"

shows script invocation without variable expansions, as desired, however not for the running script (only for scripts completed).

How to echo script invocation without variable expansion of its arguments from within the running script?

CodePudding user response:

If you can execute your script with bash -c script args, what you want is doable with the BASH_EXECUTION_STRING variable:

$ bash -c 'echo "$BASH_EXECUTION_STRING"'
echo "$BASH_EXECUTION_STRING"

This output is not easy to understand but you can see that the echo command, when executed, prints the unexpanded command. This is because the value of the BASH_EXECUTION_STRING variable is the literal: echo "$BASH_EXECUTION_STRING".

So, if your script is, for instance:

#!/usr/bin/env bash

script="$0"
cmd="$1"
shift

echo "script name: $script"
echo "command line: $cmd"
echo "parameter: $1"

you can execute it as:

$ a=42 bash -c './foo.sh "$BASH_EXECUTION_STRING" "$a"'
script name: ./foo.sh
command line: ./foo.sh "$BASH_EXECUTION_STRING" "$a"
parameter: 42
  • Related