【问题标题】:Variable from conditional statement来自条件语句的变量
【发布时间】:2014-10-17 12:36:42
【问题描述】:

我拥有一些使用 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)local result=$(find / -type f -perm -002) 如果包含在函数中将是惯用的方式。
  • 注意,在原文中,你需要引用命令替换,因为如果它扩展到多个单词,[会抱怨操作数太多。
  • 这通常是一个很长的列表。管理层强调最小的变化是偏好。因此,只是探索可能存在一些我不知道的疯狂正则表达式的可能性,它们将使用现有的内容来呈现 find 命令中的内容而不使其再次运行。

标签: bash variables conditional-statements


【解决方案1】:

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

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

【讨论】:

  • 看过之后,这似乎是最优雅的方式。我会在这个问题上向 Mgmt 发起反击。谢谢!
【解决方案2】:

如果您愿意,可以使用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."}'

【讨论】:

  • 这很聪明。我在这里学到了一些东西。感谢您的回复!
【解决方案3】:

如果您不介意没有消息 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...

【讨论】:

  • 愤怒的投票者关心会解释他/她的行为吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-25
  • 1970-01-01
  • 1970-01-01
  • 2015-11-03
  • 2014-10-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多