echo the alias command before running it
I've got a few aliases I want to clarify. They are working. How can I make this an option for many other aliases. Awk or grep? And pointers helpful. Thanks.
# IP addresses
alias myip="echo '# myip curl https://ipecho.net/plain; echo #'; curl -sS https://ipecho.net/plain; echo"
alias hazip="echo '# hazip curl https://ipv4.icanhazip.com #'; curl -sS https://ipv4.icanhazip.com"
alias ips='myip && hazip'
~ ips
# myip curl https://ipecho.net/plain; echo #
1.2.3.4
# hazip curl https://ipv4.icanhazip.com #
1.2.3.4
Example ~/.bash_aliases
file:
alias hi=" echo Hello"
You can modify this content to the following, to solve your problem:
alias hi=" type hi; echo Hello"
Output in case 1:
$ hi
Hello
Output in case 2:
$ hi
hi is aliased to `type hi; echo Hello'
Hello
How about something like this:
shopt -s extdebug
shopt -u expand_aliases
function check_for_alias {
COMMAND=$(alias $BASH_COMMAND 2> /dev/null)
if [ $? -eq 0 ]
then
tput setaf 1
echo $COMMAND
tput sgr0
${BASH_ALIASES[$BASH_COMMAND]}
return 1
fi
}
trap check_for_alias DEBUG
Explanation:
I use so called bash DEBUG trap to call a function before any command. Inside I can use $BASH_COMMAND
variable to view what is currently being called:
function check_for_alias {
echo $BASH_COMMAND
}
trap check_for_alias DEBUG
This won't do for aliases because in the handler they are already expanded - I have to disable their expanding, and then call them manually:
shopt -u expand_aliases
function check_for_alias {
# ...
${BASH_ALIASES[$BASH_COMMAND]}
}
Unfortunately, bash still tries to run an unexpanded alias, so I reveive an error telling me that command is not found. To bypass this I enable debugging and return 1 from handler if I detect that the command I run is an alias
shopt -s extdebug
function check_for_alias {
COMMAND=$(alias $BASH_COMMAND 2> /dev/null)
if [ $? -eq 0 ]
then
# ...
return 1
fi
}
Finally to print alias I use tput
to use red font. Output command is stored in $COMMAND
variable.
tput setaf 1
echo $COMMAND
tput sgr0