Bash – How to trim the carriage return from text that is being piped in bash

bashecholinuxscriptingshell-script

I'm using this command to get my last typed command:

history | cut -c 8- | tail -n 2 | head -n 1

It works very well in bash, removing the line numbers, but there is one problem I have with it, (er, annoyance, because I want just the command) and I'm piping this to the xsel clipboard manager:

It also grabs the trailing new line / carriage return…

I know in some shells you can use:

echo "text \c"

I'm not sure how to incorporate that into bash though.

Extra points for the solution that is easiest to type on the fly 🙂

Best Answer

You can get the last command in your history with the bash builtin !! and use echo -n to print that command without a newline character at the end:

echo -n !!

The !! argument will expand to the actual command string and -n makes sure the output contains no newline character.

Related Question