如何将find命令作为参数传递给bash脚本?



查找隐藏文件的命令。

命令在终端执行时被很好地识别。

但是,如果您将该命令交给bash脚本中的参数,它将被识别为无效命令。

如果将写在一起以识别特殊字符,则不会打印结果。

我想通过将find命令传递给bash脚本的参数值来执行该命令。

我该怎么办?

---------------------------------------------------------------------------------------------------------

& lt; test.sh>

#!/bin/bash
if [ -n $1 ]
then
echo $@
command=`$@`
echo $command
fi 

& lt; terminal>

[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

<执行test.sh脚本>

[root@localhost ~]# ./test.sh find / -xdev -name '.*'
find / -xdev -name . ..
find: pahts 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 '.*'

您可以尝试使用eval代替

test.sh

#!/bin/bash
if [ -n $1 ]
then
echo $@
command=$@
eval $command
fi
[ linux ]$ ./test.sh find /tmp/ -xdev -name ".*"
find /tmp/ -xdev -name ".*"
/tmp/.hidden2
/tmp/.hidden1

转义*,使其不被shell求值

./test.sh find / -xdev -name '.*'

也可以使用https://www.shellcheck.net/进行其他改进。

最新更新