简体   繁体   中英

Bash shell script function gives “find: missing argument to `-exec'” error

I wrote a function in a Bash shell script to search a Linux tree for filenames matching a pattern containing a regular expression, with colour highlighting:

function ggrep {
 LS_="ls --color {}|sed s~./~~"
 [ -n "$1" -a "$1" != "*" ] && NAME_="-iname $1" || NAME_=
 [ -n "$2" ] && EXEC_="egrep -q \"$2\" \"{}\" && $LS_ && egrep -n \"$2\" --color=always \"{}\"|sed s~^B~\ B~" || EXEC_=$LS_
 FIND_="find . -type f $NAME_ -exec sh -c \"$EXEC_\" \\;"
 echo -e \\e[7m $FIND_ \\e[0m
 $FIND_
}

eg ggrep a* lists all files starting with a under the current directory tree,

and ggrep a* x lists of files starting with a and containing x

When I run it, I get:

find: missing argument to `-exec'

even though I get the correct output when I copy and paste the line output by "echo" into the terminal. Can anyone please tell me what I've done wrong?

Secondly, it would be great if ggrep * x listed all files containing x , but * expands to a list of filenames and I need to use \\* or '*' instead. Is there a way around this? Thanks!

Terminate the find command with \\; instead of \\\\; .

find . -type f $NAME_ -exec sh -c \"$EXEC_\" \;
eval $FIND_

in the last line of the function body works fine for me.

Expansions in BASH are generally not recursive, so if you load a command from a variable, you should always use "eval" to enforce reprocessing the expanded variable as it was a fresh input. Normally quotes are not handled properly within a string that has already been expanded.

To your second problem, I think there is no satisfactory solution. The shell will always expand * before passing it to anything controlled by you. You can disable this expansion, but that is a global setting. Anyway, I think that this expansion could actually act in favor of your function. Consider rewriting it in a way that takes advantage of it. (I did not analyze whether the current version was close to that or not.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM