比方说,我有下面的代码片段,它在运行时生成一个string,我想要在shell中执行(就像我刚刚把string粘贴到terminal,然后按Enter键):
cmd="" for i in first second third do cmd="$cmd | grep $i" done cmd="cat /usr/share/dict/words $cmd" $cmd
这里的问题是pipe道字符不是这样解释的, 他们被视为cat
参数,好像我已经逃脱了他们:
cat: |: No such file or directory cat: grep: No such file or directory cat: first: No such file or directory cat: |: No such file or directory cat: grep: No such file or directory cat: second: No such file or directory cat: |: No such file or directory cat: grep: No such file or directory cat: third: No such file or directory
有没有办法“执行”pipe道字符未经转义的string? 有没有更好的方式来在运行时生成这样的代码?
我更喜欢便携式解决scheme,但bashisms是可以接受的。
要执行这个字符串,你可以使用eval $cmd