A strange problem was found during Ruby writing yesterday.
We call the shell command in Ruby. Usually we can enclose the shell command by using parentheses (the one on the left of the number key 1), for example:
'LS-l'
This lineCodeIs a string that is returned by the LS-l command.
However, when the process substitution syntax is used in the shell command, the tragedy will happen.
For example, the following command:
Cat <(echo Hello)
This command first runs the content in parentheses, and then redirects the echo Hello output to a file. The cat command displays the content of this file. <() Is a typical process substitution. Enter the preceding command directly on the terminal and the returned result is:
Hello
The preceding command is correct.
However, this command is called in ruby:
'Cat <(echo Hello )'
The output result is:
SH: 1: syntax error: "(" unexpected
The system prompts that the parentheses in the command cannot be parsed.
I created a new test. Sh file and wrote the same command in it.
Cat <(echo Hello)
Then, on the terminal:
Sh test. Sh
The following error message is returned when the parentheses in the command cannot be parsed.
But when I use
Bash test. Sh
You can get the correct output of hello.
According to Google, the standard shell does not support the process substitution syntax, but Bash does. Although Bash is used by default in Linux, standard shell is used by default for calling commands in ruby.
The problem is how to make Ruby use Bash to call shell commands.
Run man Bash to view the usage of Bash. It is found that the bash command has a-c parameter, which allows Bash to run the specified string instead of the shell file.
The following method is used in Ruby:
'Bash-C' cat <(echo Hello )''
Note that the parameters following-C must be enclosed in single quotes.
In this way, bash can also be used in Ruby to call shell commands, and there is no need to worry about using the extended syntax supported by bash.