2

I have standalone PROMPT_COMMAND= in my .bash_profile. Every time user input a command, it's being run. I want to get the first word of the last command by user.

For example, if the user runs: $ printf "Hey!", I want to access printf from my PROMPT_COMMAND.

$0 gives me -bash and $1, $2, ... gives me arguments as said on the site below. https://wiki.bash-hackers.org/scripting/posparams#the_first_argument

But how can I access the first word like printf in the above example?

Preferably, I want to use the build-in commands as much and cleanly as possible.

1

1 Answer 1

2

You could use fc:

$ printf "%s %s\n" "foo" "bar"
foo bar
$ fc -ln -1
       printf "%s %s\n" "foo" "bar"

That prints the entire command with arguments and weird spacing, so I suppose you could do:

$ fc -ln -1 | awk '{ print $1 }'
printf

EDIT: In the case you don't want pressing Return to come back as fc you could do:

$ fc -ln -1 | awk '$1 !~ /fc/ {print $1}' 

To create a function in ~/.bash_profile:

# Show last command without args
lcm () { fc -ln -1 | awk '$1 !~ /lcm/ {print $1}' ; }

Then for example:

$ date
Wed Jan 23 16:29:14 MST 2019
$ lcm
date

GNU : Bash History Built-ins

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

7 Comments

Nice trick. But, it won't work when the user's last input is nothing (entering return key) though.
@I'L'l, I've been trying it out. I am seeing two different behaviors and somehow it's not working yet. When I use it inside PROMPT_COMMAND, it prints out the last command as expected but still it's the case as long as user doesn't enter on nothing. When I call just the function, it prints out the last command, not lcm if the last command is not empty. Otherwise, it prints out lcm.
Actually, calling function also works the same as in PROMPT_COMMAND as described above. Still printing the last command if the user enter nothing. My comment above was wrong as I called lcm after lcm followed by entering nothing a few times.
Did you reload (source) your ~/.bash_profile after making the changes? . ~/.bash_profile, also are wanting to save the command into a variable?
I did reload ~/.bash_profile. I have two functions, one is where I put the command output to variable like input=$(fc -ln -1 | awk '$1 !~ /fc/ {print $1}'). Another function is just lcm function that you posted above. Both of them give me the same result.
|

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.