假设我在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字符串之一,则为true?
解决方法
请尝试以下代码:
#!/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是用于交互式查看文件信息的工具.它的输出格式化为人类,并将导致脚本中的错误.使用globs或代替.了解原因:http://mywiki.wooledge.org/ParsingLs