Bash getting stuck when printing special character
I have this function in my .profile, which creates a growl notification using iTerm2:
function growl()
{
echo -n -e $'\e]9;'"$@"'\007'
}
But, if I do declare -f growl
, Bash will become stuck and your only option is to close the current terminal window.
Output in iTerm2 + getting stucked:
growl ()
开发者_如何学Python{
echo -n -e '
Output in Terminal + bell:
growl ()
{
echo -n -e '
7;file://path/to/current/work/dir
declare -f growl
, as you probably know, is printing the complete definition of the function, including the control characters.
I suggest changing the definition so it prints the characters you want without having to have them literally included in the function definition. Bash's echo
command takes a -e
option that enables it to recognize escape sequences such as \a
for the bell character. info bash
and search for "echo" for more information.
(If you're asking how to recover once you've messed up your terminal emulator, I don't have an answer.)
EDIT: I misread the question. The problem is that you're using the $'...'
syntax, which expands escape sequences to actual control characters. Apparently declare -f
is printing the expanded strings. Just don't use the $'...'
syntax.
function growl()
{
echo -n -e '\e]9;'"$@"'\a'
}
('\a'
is equivalent to '\007'
.)
EDIT2: Fixed typo
EDIT3: Apparently in some versions of bash, echo -n -e '\e'
doesn't print an escape character, but '\033' does work. Revised solution:
function growl()
{
echo -n -e '\033]9;'"$@"'\a'
}
(The questioner is using bash 3.2.48. I've confirmed that 3.2.25 does this correctly. It's odd.)
Final solution:
Wrap it inside single-quotes and use eval:
function growl()
{
eval 'echo -e -n $'"'"'\e]9;'"'"'"$@"'"'"'\007'"'"';'
}
精彩评论