Reputation: 282
I'd like to pass every command executed in the bash shell to a variable, in order to be used to change a label showing running app.
Since newer versions of bash
have preexec hook, PS0
(expanded and displayed after reading a command and before the command is executed) and PROMPT_COMMAND
(value is interpreted as a command to execute before the printing of each primary prompt), I'm thinking of using these to achieve the change of label.
PS0
as shown below and PROMPT_COMMAND="printf '\033kBASH\033\\'"
so that label is restored to BASH
after the typed command is executed.
So for example, top
is started,
$ top
Enter
Ideally top
, as a string, would be assigned to $TO_BE_EXECUTED_APP
var which would be used to something like
PS0="print '\033k$TO_BE_EXECUTED_APP\033\\'"
These escape sequences can be used by tmux
for example to change its window label.
What I can't achieve is to populate the $TO_BE_EXECUTED_APP
with the to-be-executed command as a string.
I tried using $BASH_COMMAND
, no positive result.
Using this shell function I can manually achieve what a I need:
exelabel() {
printf "\033k$@\033\\"
"$@"
$ exelabel top
Enter
But of course I'd like this to be done automatically. Any ideas?
Upvotes: 0
Views: 345
Reputation: 26592
You can use this to get current command :
HISTTIMEFORMAT= history 1 | sed -e "s/^[ ]*[0-9]*[ ]*//"
This is what I use to display current command on xterm title :
PS0='$(printf "\e]0;%s\7" "$(HISTTIMEFORMAT= history 1 | sed -e "s/^[ ]*[0-9]*[ ]*//")")'
In your case, you can do (update after comments):
PS0='$(printf "\033k%s\033" "$(HISTTIMEFORMAT= history 1 | sed -e "s/^[ ]*[0-9]*[ ]*//")")'
or
PS0='$(printf "\033k%s\033\\\\" "$(HISTTIMEFORMAT= history 1 | sed -e "s/^[ ]*[0-9]*[ ]*//")")'
Upvotes: 1
Reputation: 282
@Philippe:
Entering
PS0='$(printf "\033k%s\033\\" "$(HISTTIMEFORMAT= history 1 | sed -e "s/^[ ]*[0-9]*[ ]*//")")'
produces these errors after each Enter
bash: command substitution: line 32: unexpected EOF while looking for matching `"'
bash: command substitution: line 33: syntax error: unexpected end of file
bash: command substitution: line 1: unexpected EOF while looking for matching `"'
bash: command substitution: line 2: syntax error: unexpected end of file
I also assigned the same line to a test variable:
testing='$(printf "\033k%s\033\\" "$(HISTTIMEFORMAT= history 1 | sed -e "s/^[ ]*[0-9]*[ ]*//")")'
If I type at prompt:
$ $testing
Enter
I get this error:
bash: $(printf: command not found
Also tried to remove space after printf, the error changes to:
bash: $(printf"\033k%s\033\\": command not found
Upvotes: 0