Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

243
Views
How to assign variable from grep output in a while loop

I wanted to create a variable for each grep regex line from Usernames.txt file. The text contains this

mario,visitor
bobmarley,staff
luigi,visitor
hailey,visitor

and so on.

I want the name from before the comma as a username and visitor as the group for the user

#!/bin/bash
sudo addgroup visitor
sudo addgroup staff

filename='Usernames.txt'

while read line; do
username=$(echo $line | grep -o '^[a-z]*[^,]')
group=$(echo $line | grep -o '[^,][a-z]*$')
sudo useradd $username -G $group -p $username
done < $filename

but the output says command username not found. So instead I tried not so efficient method

while read line; do
sudo useradd $(echo $line | grep -o '^[a-z]*[^,]') -G $(echo $line | grep -o '[^,][a-z]*$') -p $(echo $line | grep -o '^[a-z]*[^,]')
done < $filename

I want the result of each loop to be like this

sudo useradd mario -G visitor -p mario

How do I improve this? Thanks!

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Forking of multiple processes (e.g. grep) on every single loop iteration is a bad idea in general. Also, simple word splitting can be done directly in Bash, without any external processes.

Option 1:

while IFS= read -r line; do
  username="${line%,*}"
  group="${line#*,}"
  echo sudo useradd "$username" -G "$group" -p "$username"
done < "$filename"

Option 2:

while IFS=, read -r username group; do
  echo sudo useradd "$username" -G "$group" -p "$username"
done < "$filename"
over 4 years ago · Santiago Trujillo Report

0

Try this approach

while read -r name role; do
    sudo useradd $name -G $role -p $name
done < <(sed 's/,/ /' $filename)

Actually sed is enough:

sudo sed 's/\(.*\),\(.*\)/useradd \1 -G \2 -p \1/e' $filename
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!