i wanted to implement a cool feature for my PS1 prompt. I added \# string to show the command number of that command. My goal is that if a certain command is ran, the command number from \# to be set back to 1. I have some ideas but i don't know how to write it.
Is it possible to somehow export \# value as a variable, and when a command is run, the variable to be restored to the initial state. Actually this post says that its impossible.
If this doesn't work, can i create a counter that replaces \#, and then export it as a variable. That variable to be reset by a certain command.
https://www.baeldung.com/linux/bash-script-counter
Sorry i don't have enough knowladge in bash, hope i don't ask for the impossible. Thanks
Asked
Active
Viewed 394 times
0

George Rabus
- 19
- 5
-
Did you see [this question](https://unix.stackexchange.com/questions/434409/make-a-bash-ps1-that-counts-streak-of-correct-commands) ? – Zilog80 Jun 25 '21 at 12:44
-
@Zilog80 I have seen that post, but it does not answer my question. He wants his counter to reset every time he makes a mistake, in my case i want it to be reseted every time i run a certain command in shell. – George Rabus Jun 25 '21 at 12:53
-
In that case, using `if [ "\$(history| tail -n1)" -ne "
" ]; ` instead of `if [ $? -eq 0 ]; ` will not do the trick ? Beware that you can't use `!-1` in a prompt context. – Zilog80 Jun 25 '21 at 13:16 -
My bad, `if [ "\$(history| tail -n1| sed 's/^ *[0-9][0-9]* //')" -ne "
" ]; ` , to get rid of the history line number. – Zilog80 Jun 25 '21 at 13:26
1 Answers
1
I ran a quick test with a trap
. This worked for me -
$: trap 'echo "$BASH_COMMAND"; [[ "$BASH_COMMAND" =~ ^:\ *reset ]] && trap -- debug' debug
set_titlebar
set_prompt
$: date
date
Fri Jun 25 08:29:26 CDT 2021
set_titlebar
set_prompt
$: : reset
: reset
$: date
Fri Jun 25 08:29:38 CDT 2021
$:
The trap
checks $BASH_COMMAND
for your key (I used : reset
) and resets the trap
when seen. Edit in whatever key and/or code you want.

Paul Hodges
- 13,382
- 1
- 17
- 36