I'd like to run the following shell command from Ruby, which copies a string into the clipboard (on OS X), 'n' is suppressing the line break after the string caused by echo
:
echo -n foobar | pbcopy
—> works, fine, now the clipboard contains "foobar"
I've tried the following, but all of them always copy the option '-n' as well into the clipboard:
%x[echo -n 'foobar' | pbcopy]
%x[echo -n foobar | pbcopy]
system "echo -n 'foobar' | pbcopy"
system "echo -n foobar | pbcopy"
exec 'echo -n "foobar" | pbcopy'
`echo -n "foobar" | pbcopy`
IO.popen "echo -n 'foobar' | pbcopy"
What is the proper way to achieve this?
The echo command is used to display a line of text that is passed in as an argument. This is a bash command that is mostly used in shell scripts to output status to the screen or to a file.
First, note that when Ruby calls out to a shell, it typically calls /bin/sh , not Bash. Some Bash syntax is not supported by /bin/sh on all systems. This is like many other languages, including Bash, PHP, and Perl. Returns the result (i.e. standard output) of the shell command.
Explanation: echo will print the command but not execute it. Just omit it to actually execute the command.
Your problem is that -n
is only understood by the bash built-in echo
command; when you say %x[...]
(or any of your other variations on it), the command is fed to /bin/sh
which will act like a POSIX shell even if it really is /bin/bash
. The solution is to explicitly feed your shell commands to bash:
%x[/bin/bash -c 'echo -n foobar' | pbcopy]
You will, of course, need to be careful with your quoting on whatever foobar
really is. The -c
switch essentially tells /bin/bash
that you're giving it an inlined script:
-c string
If the -c option is present, then commands are read from string. If there are arguments after the string, they are assigned to the positional parameters, starting with $0.
Because echo
behaves differently in different shells and in /bin/echo
, it's recommended that you use printf
instead.
No newline:
%x[printf '%s' 'foobar' | pbcopy]
With a newline:
%x[printf '%s\n' 'foobar' | pbcopy]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With