Conditional in shell

2019-03-04 12:50发布

find . -type f -exec sh -c '  if [cat ${1} == "abc" ]   then  echo ${1} fi' _ {} \;

I got this error:

_: -c: line 1: syntax error: unexpected end of file

What I what to do here is :

find all files in this directory, print file name if file content is abc.

Thank you !

标签: shell
2条回答
Deceive 欺骗
2楼-- · 2019-03-04 13:40

Put spaces after '[' and before ']' and a ';' after the ']'

another way is to use

[ `cat ${1}` == "abc" ] && echo ${1}
查看更多
我命由我不由天
3楼-- · 2019-03-04 13:46

The problem here is that the [ (aka 'test') needs to be separated from cat by a space, like so:

find . -type f -exec sh -c 'if [ cat ${1} = "abc" ]; then  echo ${1}; fi' _ {} \;

You're also missing semicolons after the if statement and before the fi statement (it looks like you had these on separate lines originally, based on the spacing that was there, probably due to the way that you had it indented)

As pointed out in the comment below, running this will give the error message too many arguments in if []. Using double quotes around "cat ${1}" will avoid the error message, but this simply compares the expansion of "cat ${1}" with "abc". What you're probably looking for is [ "$(cat ${1})" == "abc" ]. Unfortunately, this is likely to cause problems when you compare a very long file with "abc".

You could use grep to do the test, or take a checksum (e.g. shasum) of the file, and test that against the checksum of "abc", depending on what why you're doing the test.

查看更多
登录 后发表回答