Trim trailing newline in one-liner bash alias

8

I'm trying to write a simple alias on my Mac OS X terminal to copy the current working directory. I have this:

alias cpwd="echo \`pwd\` | pbcopy; echo \"Copied \`pwd\`\""

Then I can just run the following to copy it:

$ cpwd

Problem is that echo pwd includes the newline at the end. So when I paste it, it executes immediately (if pasted in a terminal).

All I want to do is strip off the trialing newline, but nothing I find on the internet seems to work for me. Seen various solution involving sed, awk, and cut, but I can't quite get it. Seems like it would be easy to do.

Sean Adkinson

Posted 2012-12-22T00:20:43.893

Reputation: 1 975

Side note for anyone who saw this post earlier, I had to escape the back ticks in the alias, because pwd was actually being run when the aliases were being initialized – Sean Adkinson – 2012-12-27T20:09:47.597

Answers

5

I belive this should work :

alias cwd="echo -n `pwd` | pbcopy; echo \"Copied `pwd`\""

The -n says "no new line". Either that or you can always pass the output through tr and remove the new line character like that:

alias cwd="echo `pwd` | tr -d "\n" | pbcopy; echo \"Copied `pwd`\""

I'm not sure if you want to remove the trailing new line char from the first echo or from both - but i guess you can figure it out if it will work for the first one ;)

mnmnc

Posted 2012-12-22T00:20:43.893

Reputation: 3 637

Or echo $(pwd)'\c' | pbcopy; echo \"Copied $(pwd)\", where $(cmd) is (usually) equivalent to \cmd``, or pwd | tr -d "\n" | pbcopy; echo …, since echo \xyz`` (or echo $(xyz)) is generally pretty much the same as just plain xyz (assuming xyz produces exactly one line of output). – Scott – 2012-12-22T00:45:10.590

Ha, I was looking in the wrong place for answers - didn't think about man pwd. Thanks! – Sean Adkinson – 2012-12-22T00:48:49.177

Actually... just noticed it isn't in my man pwd, so I didn't stand a chance. :-) – Sean Adkinson – 2012-12-22T00:49:32.203

1printf "%s" "$(pwd)" would work too. – glenn jackman – 2012-12-22T04:05:49.517

In case you added this alias for yourself, see my comment on the original question. You actually need to escape the back ticks. Thanks for the help! – Sean Adkinson – 2012-12-27T20:12:13.173

0

I'm not sure about Mac OS X echo command but if -n argument is provided echo will not output the trailing newline:

-n do not output the trailing newline

Regards...

user181993

Posted 2012-12-22T00:20:43.893

Reputation: 1