0

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

4
  • Did you see this question ? Commented Jun 25, 2021 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. Commented Jun 25, 2021 at 12:53
  • In that case, using if [ "\$(history| tail -n1)" -ne "<your reset command>" ]; instead of if [ $? -eq 0 ]; will not do the trick ? Beware that you can't use !-1 in a prompt context. Commented Jun 25, 2021 at 13:16
  • My bad, if [ "\$(history| tail -n1| sed 's/^ *[0-9][0-9]* //')" -ne "<your reset command>" ]; , to get rid of the history line number. Commented Jun 25, 2021 at 13:26

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.