7

假设我在 bash 中有以下代码:

#!/bin/bash

bad_fruit=( apple banana kiwi )
for fname in `ls`
do
  # want to check if fname contains one of the bad_fruit
  is_bad_fruit=??? # <------- fix this line
  if [ is_bad_fruit ]
  then
    echo "$fname contains bad fruit in its name"
  else
    echo "$fname is ok"
  fi
done

如何修复 is_bad_fruit 以确保 fname 包含 bad_fruit 字符串之一?

4

2 回答 2

7

试试下面的代码:

#!/bin/bash

bad_fruit=( apple banana kiwi )
re="$(printf '%s\n' "${bad_fruit[@]}" | paste -sd '|')"

for fname in *; do
  # want to check if fname contains one of the bad_fruit
  if [[ $fname =~ $re ]]; then
    echo "$fname contains bad fruit in its name"
  else
    echo "$fname is ok"
  fi
done

照顾无用的 ls

ls是一种交互式查看文件信息的工具。它的输出是为人类格式化的,并且会导致脚本中的错误。使用 glob 或 find 代替。了解原因: http: //mywiki.wooledge.org/ParsingLs

于 2012-10-07T11:15:03.360 回答
2

另一种选择(使用grep内部循环并评估退出代码):

#!/bin/bash

bad_fruit=( apple banana kiwi )
for fname in *; do
  for fruit in "${bad_fruit[@]}"; do
    echo "$fruit"
  done | grep "$fname"
  if [ $? -eq 0 ]; then
    echo "$fname contains bad fruit in its name"
  else
    echo "$fname is ok"
  fi
done
于 2012-10-07T11:50:22.070 回答