Reputation: 15
I have a few scripts I am taking ownership of that use Bash shell, there is a find statement inside a conditional statement.
Something like this:
if [ -z $(find / -type f -perm -002) ] ; then echo "no world writable found"
where as an else I would like to display what was found instead of world write perms found
.
I can do:
echo $(find / -type f -perm -002) has world write permissions
or set variable to $(find / -type f -perm -002)
.
But was wondering if there was a a better way to do this. Is there another way to retrieve the contents of the find statement as a variable?
Upvotes: 1
Views: 338
Reputation: 37742
You just take the output and store it in a variable. If it is not empty you can print its contents. This way you only need to run the command once.
RESULT=$(find / -type f -perm -002)
if [ -z "$RESULT" ]
then
echo "no world writable found"
else
echo "$RESULT has world write permissions"
fi
Upvotes: 3
Reputation: 46833
If you don't mind not having the message no world writable found
, you can use a single find
statement, and that's all:
find / -type f -perm -002 -printf '%p has world write permissions\n'
If you need to store the returned files for future use, store them in an array (assuming Bash):
#!/bin/bash
files=()
while IFS= read -r -d '' f; do
files+=( "$f" )
# You may also print the message:
printf '%s has world write permissions\n' "$f"
done < <(find / -type f -perm -002 -print0)
# At this point, you have all the found files
# You may print a message if no files were found:
if ((${#files[@]}==0)); then
printf 'No world writable files found\n'
exit 0
fi
# Here you can do some processing with the files found...
Upvotes: 0
Reputation: 23856
You can use use sed
to insert a headline, if you like.
REPORT=$(find /tmp -type f -perm -002 | sed '1s/^/Found world write permissions:\n/')
echo ${REPORT:-No world writable found.}
Notice: your example seems to be broken, because find
can return more than one line.
And awk
can do both at once:
find /tmp -type f -perm -002 |
awk -- '1{print "Found world write permissions:";print};END{if(NR==0)print "No world writable found."}'
Upvotes: 1