shell在执行命令的时候,有一些符号需要shell能够直接能够看到的,例如管道 |,重定向 (>, <, >>, <<)等,所以此时如果有以下语句:
#! /bin/bash
pipe="|"
ls /home/ $pipe grep "out"
按照我们的想法, ls /home/ $pipe grep "out"实质就是 ls /home/ | grep "out",该语句是没有问题的,但是由于管道这些符号,shell需要能够直接在语句中看到,所以该语句执行会出现错误:
ls: cannot access |: No such file or directory
ls: cannot access grep: No such file or directory
ls: cannot access set: No such file or directory
以上出现找不到 |,grep,set的错误
所以此时我们需要通过使用eval来解决该问题,eval添加到语句的开头,在执行该语句的时候,会扫描两次该语句:第一次扫描能够替换变量对应的值,第二次扫描就是为了识别语句并运行该语句,所以改为:
#! /bin/bash
pipe="|"
eval ls /home/ $pipe grep "out" #添加eval