Bash – Escaping argument in bash script

bashgroupquotingshell

I'm writing a bash script wherein I want to check that one of the arguments passed to it is a valid group.

I have the line

if [ `grep -c -e '\b$2\b' /etc/group` -eq 0 ]; then
  echo "Error: $2 is not a valid group."
else

Which always tells me that valid groups aren't valid.

I think it's an escaping problem; I think it's grepping for a group called $2. The error message properly shows the passed argument. However I'm not sure if I'm escaping $2 within the backticks properly.

How do I get this line working?

Best Answer

Using grep's -q option is much more efficient than command substitution.

if ! grep -q -e "^$2:" /etc/group; then
    echo "Error: $2 not a valid group" >&2
fi

The issue is single quotes (') prevent shell variable expansion ($). You need to use double quotes (").

Related Question