I want to read all java Versions on my system.

for i in 'find / -name java 2>/dev/null' 
echo $i checking
$i -version

I receive an error:

find: paths must precede expression: 2>/dev/null

Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

What is the problem?


You're receiving that error from the for loop because your for loop is actually looping over one element -- the string, not the command: "find / -name java 2>/dev/null", so it is running:

echo find / -name java 2>/dev/null checking
find / -name java 2>/dev/null -version

... which is where find's error arises.

You might be trying to do:

for i in `find / -name java 2>/dev/null` 
  echo $i checking
  $i -version

... (with backticks instead of single quotes), in which case I would suggest something more along the lines of:

find / -name java -exec sh -c '"$1" -version' sh {} \; 2>/dev/null

Thanks to don_crissti for pointing out Stéphane's better version of find ... exec and for indirectly reminding me of a bash method that is one better way to find and execute results than looping over find:

shopt -s globstar dotglob
for match in /**/java
  echo match is "$match"
  "$match" -version

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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