Execute command after every command in bash
To execute a cmd before every command entered, set a trap on DEBUG. Eg.
trap date DEBUG
To execute that command before emitting a prompt, set PROMPT_COMMAND:
PROMPT_COMMAND=date
Run command after all bash commands automatically?
Found out you can do this by setting the PROMPT_COMMAND variable. In my bashrc, I added this line: export PROMPT_COMMAND='alert'
.
How to run some command before or after every Bash command entered from console?
As l0b0 suggests, you can use PROMPT_COMMAND
to do your second request and you won't have to touch PS1
.
To do your first request, you can trap
the DEBUG
pseudo-signal:
trap 'echo "foobar"' DEBUG
Pass every command executed in the bash shell to a variable
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]*[ ]*//")")'
Execute function every n commands in bash
You can trap DEBUG
signal in shell with a custom function.
runcmd() { if (( n==5 )); then n=0; pwd; else ((n++)); fi; }
trap 'runcmd' DEBUG
Change pwd
with your custom command or script.
trap 'handler' DEBUG
callshandler
after running every command in shell but won't callruncmd
when just enter is pressed in shell.
Edit: Thanks to @kojro: you can shorten this function as:
runcmd() { (( n++ % 5 )) || pwd; }
Related Topics
When Should We Use Mutex and When Should We Use Semaphore
Get Most Recent File in a Directory on Linux
How to Include All Objects of an Archive in a Shared Object
Does Linux Guarantee the Contents of a File Is Flushed to Disc After Close()
What Does O_Direct Really Mean
Extract One Word After a Specific Word on the Same Line
How to Get Full Path of a File
How to Use 'Cp' Command to Exclude a Specific Directory
How to Create a File With a Given Size in Linux
How to Run Multiple Background Commands in Bash in a Single Line
How to Add Users to Docker Container
Imagemagick Security Policy 'Pdf' Blocking Conversion
Externalizing Tomcat Webapp Config from .War File
Bash Alias Command With Both Single and Double Quotes
Are There Any Standard Exit Status Codes in Linux
Free Git Server With Web Gui a La Bitbucket/Github
Pseudo-Terminal Will Not Be Allocated Because Stdin Is Not a Terminal
Run an Untrusted C Program in a Sandbox in Linux That Prevents It from Opening Files, Forking, etc.