如何在PHP中正确执行shell命令?

时间:2017-01-19 17:42:28

标签: php shell

我有以下shell命令:

comm -3 <(sort file1) <(sort file2) | sed -e 's/^[ \t]*//' | awk -F , '{if (a[$1]) {print "^"$1","} {a[$1] = $0}}' > data2.txt

如果我通过exec运行它并逃脱所有`

exec('comm -3 <(sort file1) <(sort file2) | sed -e \'s/^[ \t]*//\' | awk -F , \'{if (a[$1]) {print "^"$1","} {a[$1] = $0}}\' > data2.txt');

失败了:

sh: 1: Syntax error: "(" unexpected

如果我逃避大括号,shell命令本身就会失败:

awk: cmd. line:1: {if \(a[$1]\) {print "^"$1","} {a[$1] = $0}}
awk: cmd. line:1:     ^ backslash not last character on line
awk: cmd. line:1: {if \(a[$1]\) {print "^"$1","} {a[$1] = $0}}
awk: cmd. line:1:     ^ syntax error
sh: 1: cannot open (sort: No such file

如何使用PHP和exec函数成功运行此shell命令?

1 个答案:

答案 0 :(得分:0)

我使用bash -c然后转义单引号解决了这个问题:

bash -c 'comm -3 <(sort {$current_file}) <(sort {$new_file}) | sed -e '"'"'s/^[ \t]*//'"'"' | awk -F , '"'"'{if (a[$1]) {print "^"$1","} {a[$1] = $0}}'"'"' > {$meta_file}'