Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: execute shell command 'echo' with '-n' option

Tags:

shell

macos

ruby

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?

like image 503
polarblau Avatar asked Feb 20 '11 18:02

polarblau


People also ask

How do you echo a command in shell script?

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.

How do you call a shell script in Ruby?

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.

Does echo execute command?

Explanation: echo will print the command but not execute it. Just omit it to actually execute the command.


2 Answers

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.

like image 165
mu is too short Avatar answered Nov 15 '22 07:11

mu is too short


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]
like image 29
Dennis Williamson Avatar answered Nov 15 '22 06:11

Dennis Williamson