Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Where is the error in this script please:

#!/bin/bash
rep="git"

files=`find' ${rep} '-type f`
for f in ${files} do
    echo $f
done

When i run find git -type f alone in the shell, it works!

share|improve this question

4 Answers 4

up vote 1 down vote accepted

Remove quotes from

files=`find '$rep' -type f`

The correct script is

#!/bin/bash
rep="git"

files=`find $rep -type f`
for f in ${files}; do
    echo $f
done

share|improve this answer
2  
Supposing you have no file names containing IFS characters. –  manatwork Oct 10 '12 at 10:53

Strings in single quotes are not interpolated. It means, you are trying to run

find ' ${rep} '-type f

Remove the single quotes. If you really need to quote the $rep (e.g. because it contains spaces), use double quotes:

files=`find "$rep" -type f`

Note that there are no spaces inside the double quotes. You are searching 'git', not ' git ', right?

share|improve this answer

Don't store the output of find in a variable. It's unreliable and inefficient. Inefficient, because find has to finish running before you start processing its output; this makes a difference on a large directory tree. Unreliable because even if you got the command syntax right, the output of find would consists of a list of file names separated by newlines. This is ambiguous unless the file names are known not to contain newlines. Furthermore, you aren't parsing the output correctly: with an unquoted command substitution $(…), the result of the command is broken into separate words wherever there's whitespace (not just newlines), and the words are interpreted as shell glob patterns. To avoid this processing, use "$(…)" (always put double quotes around variable and command substitutions: "$foo", "$(foo)"); this is no good here since you need to separate the file names.

find has a built-in feature to process the resulting files: the -exec action. Use it. That's what it's for.

find "$rep" -type f -exec echo {} \;

If you need to run an arbitrary shell snippet and not just a single command on each file, invoke a shell as the command. To avoid mangling the file name, pass it as a parameter to the shell.

find "$rep" -type f -exec sh -c '
  echo "$0"
  # more shell commands ...
' {} \;
share|improve this answer

Add space after ' and before -type

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.