Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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 :)

share|improve this question

2 Answers 2

up vote 7 down vote accepted

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.

share|improve this answer

If I am reading your question correctly, you need to remove the trailing newline. Try this perl bit: `perl -ne 'chomp and print'

Examples:

[root@talara test]# ls -la
total 20
drwxr-xr-x   3 root root 4096 Jun  7 21:30 .
dr-xr-x---. 28 root root 4096 Jun  8 08:42 ..
-rw-r--r--   1 root root    0 Jun  7 15:10 FILE1
drwxr-xr-x   3 root root 4096 Jun  7 14:49 ham
-rw-r--r--   1 root root   36 Jun  7 21:31 t
-rw-r--r--   1 root root   11 Jun  7 16:21 test

[root@talara test]# ls -la | perl -ne 'chomp and print'
total 20drwxr-xr-x   3 root root 4096 Jun  7 21:30 .dr-xr-x---. 28 root root 4096 Jun  8 08:42 ..-rw-r--r--   1 root root    0 Jun  7 15:10 FILE1drwxr-xr-x   3 root root 4096 Jun  7 14:49 ham-rw-r--r--   1 root root   36 Jun  7 21:31 t-rw-r--r--   1 root root   11 Jun  7 16:21 test

And to make it easy for typing over and over and on the fly you can make an alias: alias chomp="perl -ne 'chomp and print'"

share|improve this answer
    
clever - thank you –  cwd Jun 8 '12 at 19:39

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.