A problem on alias for bash function when re-source the script
Last updated: Apr 13, 2021 |
Publish date: Feb 19, 2021
The system infomation is
$ cat /etc/redhat-release
Red Hat Enterprise Linux Server release 7.6 (Maipo)
$ uname -a
Linux xxx.cn 3.10.0-957.el7.x86_64 #1 SMP Thu Oct 4 20:48:51 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
Object: wrapper top
to make it clean the screen after its exit
Becase the top
command in the system do not clean the screen when it exit, I want to wrapper it by a function
and alias
command in the ~/.bashrc
file.
function __top () {
tput smcup;
top "$@";
__RET=$?;
tput rmcup;
if [ $__RET -ne 0 ]; then
top "$@";
fi;
return $__RET
}
alias top=__top
Issue
The problem of the above code is that when I source the file .bashrc
for a second time, the top
command will leave
the screen black with nothing (Ctrl+C
can quit).
Solution
Because the function __top
use top
, loading it a second time will result in a recursive call.
Therefore, we must unalis top before defining the function.
The solution looks like this
# unalias top if it exists
if alias top >/dev/null 2>&1 ; then
unalias top
fi
function __top () {
tput smcup
top "$@"
__RET=$?
tput rmcup
if [ $__RET -ne 0 ]; then
top "$@"
fi
return $__RET
}
alias top='__top'