Home > Enterprise >  How do I pass the find command to the bash script as a argument?
How do I pass the find command to the bash script as a argument?

Time:12-26

This command is a command to find hidden files.

The command is well recognized when executed at terminal.

However, if you turn the command over to the argument in the bash script, it will be recognized as an invalid command.

If you write \ together to recognize special characters, the results will not be printed.

I want to execute the command by passing the find command to the argument value of the bash script.

What should I do?

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

<test.sh>

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

<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

<execute test.sh script >

[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 '.*'

CodePudding user response:

You can try using eval instead

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

CodePudding user response:

Escape the * so it's not evaluated by the shell

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

Also, use https://www.shellcheck.net/ for other improvements.

  • Related