Using awk to append text to the end of a line in /etc/group

I am writing a script to automate some tasks and I need to add a user to a group in /etc/group. I'm trying to use this command:

sudo bash -c "awk '{if (/^moli/) {$0=$0"$uservar,"}; print' /etc/group > /etc/group"

The issue I'm running into is I get

awk: cmd. line:1: {if (/^moli/) {-bash=-bashtestuser1,}; print
awk: cmd. line:1:                     ^ syntax error
awk: cmd. line:1: {if (/^moli/) {-bash=-bashtestuser1,}; print
awk: cmd. line:1:                                             ^ unexpected newline or end of string

If I change the ' ' to "" I get: -bash: syntax error near unexpected token '('


There are a lot of issues in your small code:

  • Single quotes inside double quotes do not prevent variable substitution.
    So, $0 expands to /bin/bash. See here.

  • You're actually really lucky that your command failed!! If working, it would have emptied your /etc/group file and you would have serious problems.
    In the moment you issue command > file, file gets opened and emptied for writing, and your command will see an empty file.

    Better use > file.temp && mv file.temp file or awk -i inplace ....

  • Instead of adding bash variables directly in awk code, use awk -v var=$var option and use var inside awk.


So, what to do ?

You don't need this duplicate quoting hell, you could simply use:

sudo awk -i inplace '...' file

or

awk '...' file | sudo tee file.temp && sudo mv file.temp file

or for your case the better suited sed:

sudo sed -i '...' file

However, you should not change /etc/group manually at all.

Add a user with usermod (as suggested here):

sudo usermod -a -G groupName userName