我有一个包含目录名称的文件:
my_list.txt
:
/tmp
/var/tmp
如果该名称已存在于文件中,我想在添加目录名称之前检查 Bash。
最佳答案
grep -Fxq "$FILENAME" my_list.txt
如果找到该名称,则退出状态为 0(真),否则为 1(假),因此:
if grep -Fxq "$FILENAME" my_list.txt
then
# code if found
else
# code if not found
fi
说明
这里是the man page for grep
的相关部分:
grep [options] PATTERN [FILE...]
-F
,--fixed-strings
Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched.
-x
,--line-regexp
Select only those matches that exactly match the whole line.
-q
,--quiet
,--silent
Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the
-s
or--no-messages
option.
错误处理
正如评论中正确指出的那样,上述方法默默地对待错误情况,就好像找到了字符串一样。如果您想以不同的方式处理错误,则必须省略 -q
选项,并根据退出状态检测错误:
Normally, the exit status is 0 if selected lines are found and 1 otherwise. But the exit status is 2 if an error occurred, unless the
-q
or--quiet
or--silent
option is used and a selected line is found. Note, however, that POSIX only mandates, for programs such asgrep
,cmp
, anddiff
, that the exit status in case of error be greater than 1; it is therefore advisable, for the sake of portability, to use logic that tests for this general condition instead of strict equality with 2.
要抑制 grep
的正常输出,您可以将其重定向到 /dev/null
。请注意,标准错误仍然是未定向的,因此 grep
可能打印的任何错误消息最终都会如您所愿地出现在控制台上。
为了处理这三种情况,我们可以使用case
语句:
case `grep -Fx "$FILENAME" "$LIST" >/dev/null; echo $?` in
0)
# code if found
;;
1)
# code if not found
;;
*)
# code if an error occurred
;;
esac
关于string - 如何使用 Bash 测试文件中是否存在字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4749330/