每个人都说eval是邪恶的,你应该用$()代替.但是我遇到了一种情况,即$()内部的unquoting处理方式不同.
背景是我经常被包含空格的文件路径烧掉,所以喜欢引用所有这些路径.关于想知道我的所有可执行文件来自何处的更多偏执狂.更偏执,不相信自己,所以能够显示我即将运行的创建命令.
下面我尝试使用eval与$()的变体,以及是否引用命令名称(因为它可能包含空格)
BIN_LS="/bin/ls"
thefile="arf"
thecmd="\"${BIN_LS}\" -ld -- \"${thefile}\""
echo -e "\n Running command '${thecmd}'"
$($thecmd)
Running command '"/bin/ls" -ld -- "arf"'
./foo.sh: line 8: "/bin/ls": No such file or directory
echo -e "\n Eval'ing command '${thecmd}'"
eval $thecmd
Eval'ing command '"/bin/ls" -ld -- "arf"'
/bin/ls: cannot access arf: No such file or directory
thecmd="${BIN_LS} -ld -- \"${thefile}\""
echo -e "\n Running command '${thecmd}'"
$($thecmd)
Running command '/bin/ls -ld -- "arf"'
/bin/ls: cannot access "arf": No …Run Code Online (Sandbox Code Playgroud)