来自条件陈述的变量

时间:2014-10-17 12:36:42

标签: bash variables conditional-statements

我有一些脚本我正在使用Bash shell,在条件语句中有一个find语句。

这样的事情:

if [ -z $(find / -type f -perm -002) ] ; then echo "no world writable found"

作为其他人,我想显示找到的内容而不是world write perms found

我能做到:

echo $(find / -type f -perm -002) has world write permissions

或将变量设置为$(find / -type f -perm -002)

但是想知道是否有更好的方法来做到这一点。是否有另一种方法可以将find语句的内容检索为变量?

3 个答案:

答案 0 :(得分:3)

您只需获取输出并将其存储在变量中。如果它不是空的,您可以打印其内容。这样,您只需要运行一次命令。

RESULT=$(find / -type f -perm -002)
if [ -z "$RESULT" ]
then
    echo "no world writable found"
else
    echo "$RESULT has world write permissions"
fi

答案 1 :(得分:1)

如果您愿意,可以使用sed来插入标题。

REPORT=$(find /tmp -type f -perm -002 | sed '1s/^/Found world write permissions:\n/')
echo ${REPORT:-No world writable found.}

注意:您的示例似乎已被破坏,因为find可以返回多行。

并且awk可以同时执行这两项操作:

find /tmp -type f -perm -002 | 
awk -- '1{print "Found world write permissions:";print};END{if(NR==0)print "No world writable found."}'

答案 2 :(得分:0)

如果您不介意没有消息no world writable found,则可以使用单个find语句,这就是全部:

find / -type f -perm -002 -printf '%p has world write permissions\n'

如果您需要存储返回的文件以供将来使用,请将它们存储在一个数组中(假设为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...
相关问题