为什么在shell脚本中使用<()会导致语法错误?

Apo*_*llo 2 linux bash shell

我正在编写一个调用myShellScript.sh其中的shell脚本,其中包含以下文本:

echo *** Print out this line ****
diff <(./myProgram) <(./otherProgram)
Run Code Online (Sandbox Code Playgroud)

但是,当我运行时,sh myShellScript.sh我收到以下错误:

-bash-4.2$ sh myShellScript.sh 
myShellScript.sh **** Print out this line **** myShellScript.sh
myShellScript.sh: line 2: syntax error near unexpected token `('
myShellScript.sh: line 2: `diff <(./myProgram) <(./otherProgram)'
Run Code Online (Sandbox Code Playgroud)

Sto*_*ica 5

使用<(...)运算符替换进程是一项bash功能.您收到该错误消息是因为您的脚本正在执行其他内容(例如dash)或旧版本bash,或者bash在POSIX兼容模式下运行,并禁用了进程替换等非POSIX功能(谢谢,@ check!)

如果您想使用功能齐全的bash执行脚本,您有两个选择:

  1. 运行脚本bash:

    bash myShellScript.sh 
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将脚本的第一行设置为#!/bin/bash(或bash系统中的路径),然后运行如下脚本:

    ./myShellScript.sh 
    
    Run Code Online (Sandbox Code Playgroud)