1

I know there are some bash variables that are assigned after executing a Bash command. Some of them are $? to get the return value of the process or $BASH_COMMAND to get the actual call line, $1, $2 etc to retrieve the call args, etc.

A simple trick with trap would (taken from this question) allow me to store the last executed command:

alariva@trinsic:~/test$ trap 'previous_command=$this_command; this_command=$BASH_COMMAND' DEBUG
alariva@trinsic:~/test$ ls -l #I want to read this comment
total 0
-rw-rw-r-- 1 alariva alariva 0 Aug 23 01:30 readme.md
alariva@trinsic:~/test$ echo $previous_command
ls -l
alariva@trinsic:~/test$ echo $?
0

I need to get the comment that may come after the last command, but I'm not aware of any variable that would store it. Is there any way to read it?

I would like to get a similar behavior to this:

alariva@trinsic:~/test$ ls -l #I want this comment
readme.md
alariva@trinsic:~/test$ echo $BASH_COMMENT
I want this comment
alariva@trinsic:~/test$ 

Of course, the current situation is that I cannot retrieve any info from this:

alariva@trinsic:~/test$ echo $BASH_COMMENT

alariva@trinsic:~/test$ 

I'm also aware that comments may be completely stripped out after Bash interprets the call, so in that case I wonder if there exists a workaround (like a hook or something) to read it before it actually reaches bash.


So far, this is what I achieved:

alariva@trinsic:~/test$ ls -l #tosto
total 0
alariva@trinsic:~/test$ LAST=`fc -l | cut -c 6- | tail -n2 | head -n1`
alariva@trinsic:~/test$ echo "${LAST##*\#}"
tosto
alariva@trinsic:~/test$

Not sure if this is the best possible solution and if it'd work on all scenarios but looks like the behavior I want to achieve. Is there any built-in/alternative way to get this?

alariva
  • 2,051
  • 1
  • 22
  • 37

1 Answers1

0

The closest solution I came up so far is the following.

alariva@trinsic:~/test$ ls -l #tosto
total 0
alariva@trinsic:~/test$ LAST=`fc -l | cut -c 6- | tail -n2 | head -n1`
alariva@trinsic:~/test$ echo "${LAST##*\#}"
tosto
alariva@trinsic:~/test$

While that will work for most of the scenarios I use, it still will fail to get the full comment on some scenarios where more than one # is found:

alariva@trinsic:~/test$ ls -l #tosto #only partial
total 0
alariva@trinsic:~/test$ LAST=`fc -l | cut -c 6- | tail -n2 | head -n1`
alariva@trinsic:~/test$ echo "${LAST##*\#}"
only partial
alariva@trinsic:~/test$

Improvements on this answer are welcome.

alariva
  • 2,051
  • 1
  • 22
  • 37