0

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 '('

pLumo
  • 26,947
  • 1
    What is the sense of using bash -c here? Can't you just do awk ... | sudo tee /etc/group ? However, I would strongly suggest not to manually edit /etc/group file. If you do anything wrong, you might lock yourself out of your system. The least you have to do is make a backup of the file. Also, what is $uservar? Seems you rather want to use sudo sed -i ... – pLumo Jun 07 '21 at 18:18
  • 1
    Do not edit /etc/group manually! Rather use usermod command. See here. – pLumo Jun 07 '21 at 18:23
  • I tried usermod -a -G moli username as a test. I checked to see if the user showed up in /etc/group but they're not there. – TL_Arwen Jun 07 '21 at 18:34
  • You might need to logout/login to see the changes I guess, that is also written in the answer from the link ;-) – pLumo Jun 07 '21 at 18:41
  • It doesn't show in /etc/groups but if I run groups username it shows there. – TL_Arwen Jun 07 '21 at 18:45

1 Answers1

1

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
pLumo
  • 26,947