来自条件语句的变量
我有几个脚本我正在使用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语句的内容作为变量?
您只需输出并将其存储在一个变量中。如果它不是空的,你可以打印它的内容。这样你只需要运行一次该命令。
RESULT=$(find/-type f -perm -002)
if [ -z "$RESULT" ]
then
echo "no world writable found"
else
echo "$RESULT has world write permissions"
fi
看过后,这似乎是最优雅的方式。我会在这方面推回Mgmt。谢谢! – d3051 2014-10-17 13:37:21
如果您愿意,您可以使用使用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."}'
这很聪明。我在这里学到了东西。感谢您的答复! – d3051 2014-10-17 13:36:29
如果你不介意不具有消息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...
愤怒downvoter护理会解释他/她的行为? – 2014-10-23 19:49:36
将查找结果赋给变量有什么不对? – ceving 2014-10-17 12:40:57
'result = $(find/-type f -perm -002)'或'local result = $(find/-type f -perm -002)'如果包含在函数中将是惯用的方式。 – helpermethod 2014-10-17 12:47:37
请注意,在原文中,您需要引用命令替换,因为如果它扩展为多个单词,'['会抱怨太多的操作数。 – chepner 2014-10-17 12:54:33