小编Tig*_*rex的帖子

转义 [ 在 grep

我从标准输入读取字符串,我想显示匹配字符串的用户。问题是,如果用户输入字符 '[' 或包含它的字符串。

grep -F不起作用,因为该行必须以字符串开头(^ - 这是一个带 -F 的简单字符)。此外,getent $user不会很好,因为我只需要用户名而不是 id。

if [[ "$user" == *"["* ]]; then
    echo -e "Invalid username.\n"
    continue
fi

if ! getent passwd | grep "^$user:"; then
    echo -e "Invalid username.\n"
    continue
fi
Run Code Online (Sandbox Code Playgroud)

这是'['的解决方法,还有其他方法吗? awk最有可能完成这项工作,但我对此一无所知,我对 grep 感兴趣。

grep bash shell-script quoting

4
推荐指数
2
解决办法
5040
查看次数

标签 统计

bash ×1

grep ×1

quoting ×1

shell-script ×1