如何将find命令作为参数传入Bash脚本并正常执行?
解决Bash脚本接收带引号参数执行失败的问题
问题场景
需要将查找隐藏文件的find / -xdev -name '.*'命令作为参数传入Bash脚本执行,该命令在终端直接执行正常,但传入脚本时要么被识别为无效命令,要么添加转义后无法输出结果。
原测试脚本test.sh内容:
#!/bin/bash if [ -n $1 ] then echo $@ command=`$@` echo $command fi
终端直接执行find命令的正常结果:
[root@localhost ~]# find / -xdev -name '.*' /usr/lib/debug/usr/.dwz /usr/lib64/.libgcrypt.so.11.hmac /usr/lib64/.libcrypto.so.1.0.2k.hmac /usr/lib64/.libcrypto.so.10.hmac /usr/lib64/.libssl.so.1.0.2k.hmac /usr/lib64/.libssl.so.10.hmac /usr/share/man/man1/..1.gz /usr/share/man/man5/.k5identity.5.gz /usr/share/man/man5/.k5login.5.gz /usr/share/kde4/apps/kdm/themes/CentOS7/.colorlsCZ1 /home/test01/.bash_logout /home/test01/.bash_profile /home/test01/.bashrc /home/test01/.bash_history /home/test02/.bash_logout /home/test02/.bash_profile /home/test02/.bashrc /home/test02/.bash_history
脚本执行异常情况:
[root@localhost ~]# ./test.sh find / -xdev -name '.*' find / -xdev -name . .. find: paths must precede expression: .. Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression] [root@localhost ~]# ./test.sh find / -xdev -name \'.*\' find / -xdev -name '.*'
问题原因
- 参数展开错误:未给
$@加双引号时,shell会将'.*'解析为当前目录下的隐藏文件(.和..),导致find命令的参数被错误拆分,触发语法错误。 - 变量引用不规范:
[ -n $1 ]未加双引号,当参数为空或含空格时会出现逻辑错误;使用内置命令名command作为变量名,存在冲突风险;反引号` `的命令替换方式可读性差,且嵌套处理复杂。
修复方案
修改脚本,确保参数被正确传递和解析:
#!/bin/bash # 检查是否有传入参数,双引号包裹避免空参数或含空格参数的逻辑错误 if [ -n "$1" ]; then # 双引号包裹$@,保留每个参数的原始格式 echo "执行的命令:$@" # 用$()做命令替换,双引号包裹$@保证参数完整传递 result="$("$@")" echo "执行结果:" echo "$result" fi
测试验证
执行修复后的脚本:
[root@localhost ~]# ./test.sh find / -xdev -name '.*' 执行的命令:find / -xdev -name '.*' 执行结果: /usr/lib/debug/usr/.dwz /usr/lib64/.libgcrypt.so.11.hmac /usr/lib64/.libcrypto.so.1.0.2k.hmac /usr/lib64/.libcrypto.so.10.hmac /usr/lib64/.libssl.so.1.0.2k.hmac /usr/lib64/.libssl.so.10.hmac /usr/share/man/man1/..1.gz /usr/share/man/man5/.k5identity.5.gz /usr/share/man/man5/.k5login.5.gz /usr/share/kde4/apps/kdm/themes/CentOS7/.colorlsCZ1 /home/test01/.bash_logout /home/test01/.bash_profile /home/test01/.bashrc /home/test01/.bash_history /home/test02/.bash_logout /home/test02/.bash_profile /home/test02/.bashrc /home/test02/.bash_history
此时脚本可正确接收并执行带引号的find命令,输出正常结果。
内容的提问来源于stack exchange,提问作者KKong Kong
相关产品推荐
相关产品推荐

