其他用户的 grep bashrc 用于检查变量

grep bashrc of other user for checking variable

我正在尝试 grep 用户的 bashrc 以检查某行是否已存在。 我试过这个:

if [ [ su -  -c "cat ~/.bashrc | grep  | wc -c | tr -d ' '"  ] -gt 0 ]
if [ su -  -c "cat ~/.bashrc | grep  | wc -c | tr -d ' '"  ]

$1 是用户名

$2 是变量名

在执行中

+ '[' su - user -c 'cat ~/.bahsrc | grep PATH | wc -c | tr -d '\'' '\''' ']'
line xxx: [: too many arguments

这样可以吗?我是否需要使用 return 值(实际上全部 $? = 0)?

如果您只是检查 行是否存在 ,则无需涉及 wctr 或其他任何内容;这应该足够了:

if su -  -c "grep -q '' ~/.bashrc" ; then
  echo line exists in file
else
  echo line does not exist in file
fi

如果 </code> 的内容在 <code>~/.bashrc 中找到,这将回显 line exists in file

为了帮助理解这里发生了什么,请记住 if 语句的语法是(来自 bash 手册页):

if list; then list; [ elif list; then list; ] ... [ else list; ] fi

其中 list 是一个或多个命令。在这种情况下,我们使用 grep 命令的退出代码来确定表达式的 "truth"。