Eduard Petru Eduard Petru - 29 days ago 12
Linux Question

for loop linux scripting: Syntax error: Bad for loop variable

I'm at the very beginning in scripting. ( I have just finished Linux LPI essentials)
I have the following challenge:

Create a new group. Each group must have a unique name. The script must check to ensure that no duplicate group names exist on the system. If a duplicate is found, an error needs to be reported, and the administrator must try another group name.

Here is my "script":

#!/bin/bash

echo "Please enter a group name"
read gname

for $gname in /etc/group; do
echo "Please enter another group name"
read gname
done

groupadd $gname
echo "Group $gname has been created"


this is the error I received.

Please enter a group name
alexandru
test.sh: 6: test.sh: Syntax error: Bad for loop variable

Answer Source

I DID IT!!! Thank you Guys!!! ( Kalpa Welivitigoda and Rawkode )

!/bin/bash

echo "Please enter a group name"
read gname
groupadd $gname
while [ $? != 0 ];
do
echo "Enter a new group name"
read gname
groupadd $gname
done