It can't be done generally, but using the history
command in bash
it can maybe sort of be done, provided certain conditions are met:
history
has to be turned on.
Only one shell has been running, or accepting new commands, (or failing that, running myscript.sh), since the start of myscript.sh.
Since command lines with leading spaces are, by default, not saved to the history, the invoking command for myscript.sh must have no leading spaces; or that default must be changed -- see Get bash history to remember only the commands run with space prefixed.
The invoking command needs to end with a &
, because without it the new command line wouldn't be added to the history until after myscript.sh was completed.
The script needs to be a bash
script, (it won't work with /bin/dash
), and the calling shell needs a little prep work. Sometime before the script is run first do:
shopt -s histappend
PROMPT_COMMAND="history -a; history -n"
...this makes the bash
history heritable. (Code swiped from unutbu's answer to a related question.)
Then myscript.sh might go:
#!/bin/bash
history -w
printf 'calling command was: %s\n' \
"$(history | rev |
grep "$0" ~/.bash_history | tail -1)"
Test run:
echo googa | ./myscript.sh &
Output, (minus the "&
" associated cruft):
calling command was: echo googa | ./myscript.sh &
The cruft can be halved by changing "&
" to "& fg
", but the resulting output won't include the "fg
" suffix.