3

The command number in bash specifies the number of commands typed since logging in as that user to whatever terminal you have open. It can be seen in your PS1 with \#, such as in

export PS1="\! \# \\$"

I would like to reset this number at times. I can reset the history number in bash with history -c among other things but I cannot figure out how to reset the command number.

I saw someone once with a PS1 that would reset a counter to 0 whenever they typed a command with a nonzero exit status. I thought that was funny, and am trying to recreate it, as I cannot find this online. I would not like to reset the history number since this also prevents me from searching through past commands. edit: I got this functionality without resetting the command number; see here

Is there a way to display the command number in bash without PS1, or to set it somehow?

1
  • I think that \# is actually local to the bash, not shared among all terminals openned since logging.
    – ChrisAga
    Commented Jun 8, 2020 at 18:23

1 Answer 1

2

I'm going to say "no", or "not in bash 4.4", or "not without changing the code and re-compiling", as that value is in the variable named current_command_number, and it is only ever referenced and incremented:

$ grep -r current_command_number *.c
eval.c:extern int current_command_number, current_command_line_count, line_number;
eval.c:       current_command_number++;
shell.c:int current_command_number = 1;
shell.c:  current_command_number = 1;
y.tab.c:extern int current_command_number;
y.tab.c:              temp = itos (current_command_number);

shell.c sets it to 1 twice: during the instantiation of the variable and in the shell_reinitialize function. That function also resets the prompt, re-initializes history, and deletes all variables and functions. That function is only called once, from main().

The only external visibility to that variable is in the decode_prompt_string function, which itself is called when the prompt is supposed to be displayed or redisplayed.

3
  • Thanks! I think I have found another way to do what I want. I am instead trying to use a counter variable and PROMPT_COMMAND to check if my last command had a nonzero exit status. PROMPT_COMMAND="if [ $? -eq 0 ]; then ((counter++)); else counter=0; fi" This will always increment counter, never reset it. Could you explain what I am doing wrong on this? Commented Mar 30, 2018 at 0:24
  • That sounds like it'd be an excellent new question!
    – Jeff Schaller
    Commented Mar 30, 2018 at 0:26
  • Fair. Posted here if you're willing to take a look. Thanks again. Commented Mar 30, 2018 at 0:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .