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

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

Don't try to parse /etc/group, instead - rely on groupadd to perform it's job correctly.
When you use groupadd and the name the group already exists, it will exit with a non-zero code.
if [[ $? != 0 ]];
then
echo "Error, group already exists"
fi
So to loop this until you get a correct group:
#!/usr/bin/env bash
echo "Enter group name: "
read group
until groupadd $group
do
read group
done
echo "${group} created"

You probably run it with sh, not bash. Try bash fileName.sh, or ./fileName.sh if it's executable, but not sh fileName.sh.

You may need to iterate over the content of /etc/group, try the following,
for $gname in $(cat /etc/group); do
On a different note, it is better to check whether the new group name also is an existing group name.

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

Related

For each parameters, script checks if there exists a user of such username. If exists script prints all processes run by this user

#!/bin/bash
if [ $# -ne 1 ]
then
echo "Script Should Have Atleast 1 Parameter"
exit
fi
USER=$1
echo $USER
if [ $? -eq 0 ]
then
echo " Yes the User Exists"
else
echo "No , The User Doesnt Exists"
fi
My problem here is whatever the input i give, it shows yes the user exists.
And can anyone suggest me a command to print out all the process runs by this user
Should i use awk , or grep
Well, first of all, you are not checking if user exists, but ultimately if command echo $USER didn't fail. You will need to implement proper user check.
Good way how to check if arbitrary user exists would be something like this, using command id.
if id "${1}" &> /dev/null; then
echo 'user found'
else
echo 'user not found'
fi
Next you want to list all processes belonging to this user. You will need ps. There are many ways how ps can format output. Be sure to check manual page of ps. Here is example which lists command and pid of all processes belonging to user in "$1".
ps -eo pid,comm --user $(id -u "${1}")
At last, running check using id and only then using ps for process list is inefficient at least. In your use-case, you can simply run ps and check if it was successful. If not, you can show warning that user was not found.
#!/bin/bash
if ! ps -u "$1" 2> /dev/null; then
echo 'user not exists!'
exit 1
fi

Reading multiple files/folders with shellscript

I am using the read command to capture the files/folder names and further checking if they exist but below script only works with a single file/folder and does not work to capture multiple files/folders. Please help!
Thank you!
echo -n "Please enter a name of file/folder you wish to backup: "
read FILE
while [ ! -e "$FILE" ] ;do
read -p "The file ["$FILE"] does not exist."
echo -n "Please enter a name of file/folder you wish to backup: "
read FILE
done
I recommend taking an approach similar to this:
You can use CTRL + C to force an exit.
Please note that this should really be an if statement like to
ensure proper flow of logic as && || does not equate to if
then else logic
if [ "foo" = "foo" ]; then
echo expression evaluated as true
else
echo expression evaluated as false
fi
https://github.com/koalaman/shellcheck/wiki/SC2015

How to check if a group exists and add if it doesn't in Linux Shell Script

this is a summary of what i want my code to do:
if (group exists)
then
(add user to group)
else
(create group)
(add user to group)
fi
I am using the Ubuntu virtual machine but all of the results i have found on similar sites do not work.
The grep statement in the solution of rups has some flaws:
E.g. grepping for a group admin may return true ("group exists") when there is a group lpadmin.
Either fix the grep-query
grep -q -E "^admin:" /etc/group
or use
if [ $(getent group admin) ]; then
echo "group exists."
else
echo "group does not exist."
fi
This script may help you:
read -p "enter group name: " group
if grep -q $group /etc/group
then
echo "group exists"
else
echo "group does not exist"
fi
Grepping /etc/group works, but only on a machine where /etc/nsswitch.conf has:
group: files
meaning that only /etc/group is consulted when determining available groups. Use either of these (by name or by gid):
getent group <groupname>
getent group <groupid>
for a more generic solution, checking the exit status: 0 means "exists", non-zero means "does not exist". For example, to check to see if group 'postgres' exists, and create it if it does not (assuming bash shell, running as a user able to create new groups) run:
/usr/bin/getent group postgres 2>&1 > /dev/null || /usr/sbin/groupadd postgres
I've found it more useful, to compose andiba's solution into a proper function:
function grpexists {
if [ $(getent group $1) ]; then
echo "group $1 exists."
else
echo "group $1 does not exist."
fi
}
This can for e.g be invoked into your environment by including this function in your /etc/bash.bashrc*, such that you can then check for the existence of a group, using the following spell:
grpexists group_name
Which should then return one of:
group group_name exists.
or
group group_name does not exist.
Single line:
$getent group <-groupname-> || groupadd <-groupname->
Here are 3 commands which should work:
group=sudo
grep -qw ^$group /etc/group || groupadd $group
usermod -aG $group $USER
Or one, when you use -f/--force (exit successfully if the group already exists):
groupadd -f mygroup && usermod -aG mygroup $USER
$ groupadd --help
Usage: groupadd [options] GROUP
Options:
-f, --force exit successfully if the group already exists,
and cancel -g if the GID is already used
So you can do simply:
groupadd -f some_new_grp
Geeks great solutions and guidance, thanks for sharing here are my 2 cents to make our lives simpler or lazier :-) I could use to complement an useradd script I have to add several users at once. I'm wondering how it would look like inside a for
in loop for several groups: group1, group2, group3...group6
Then useradd to the system something like this?
for g in $( cat fewgroups.txt ); do
groupadd $g
echo "Group:" $g "Exist not added moving on"
else
echo "Group:" $g "added successfully!"
# Then create the users
for u in $( cat 100sofusers.txt ); do
useradd -m -g group1 -G group2,wheel -d /home/$u -c "Just anothe SiFiGeek" -s /bin/bash $u
echo "userID:" $u "added successfully!"
echo $u:$randompw | chpasswd
echo "Password for userID:" $u "changed successfully"
done

Linux script groupadd

I have a groupadd script:
#/bin/bash
echo -n "Enter new group name: "
read group
if egrep "^$group" /etc/group; then
cut -d: -f1 /etc/group
echo "!!Group $group already exists!!"
echo -n "Enter different group name: "
read name
groupadd $name
echo "Group $name was created."
else
groupadd $group
echo "Group $group was crated."
fi
This script works perfectly fine. But I run into small problem which I have trouble to figure it out how to deal with that problem.
The problem starts when I'm entering Hello and there is already group Hello. It says group Hello already exists. The line Enter different group name pops and I again enter Hello. It shows this which bothers me because I can't deal with it:
groupadd: group "Hello" already exists
Group Hello was created.
But I want to do another group check loop when entering for second time Hello and not ending the script like in the example above.
So if there will be someone to show me how to deal with this I'll be happy :)
Thanks :)
First of all you have to use getent group $group > /dev/null 2>&1 instead of manual grepping. Second, you may do a while loop like while read x; do; … ; done.

String Bash scripting if then statement fails

I am currently writing a script that will allow me to add groups via user input. I am on the portion of my script where the user types the group name in and it compares it against /etc/group and lets the user know if it needs to be added or not. I have tested this against a group that I know for a fact is not on my system and it only reads the first statement in my loop. Could someone tell me where I am going wrong?
#!/bin/bash
echo "This script will allow you to enter Groups and Users needed for new builds"
echo
echo
echo
echo
# Setting Variables for Group Section
Group=`cat /etc/group |grep "$group"`
echo -n "Please enter the group name that you would like to search for..press [ENTER] when done: " # Request User input to obtain group name
read group
echo "Searching /etc/group to see if the group "$group" exists." # Checking to see if the group exists
if [ "$group" != "$Group" ]; then
echo "The group already exist. Nothing more to do buddy."
else
echo "We gotta add this one fella..carry on."
If you're on Linux, and thus have getent available:
printf "Group to search for: "
read -r group
if getent group "$group" >/dev/null 2>&1; then
echo "$group exists"
else
echo "$group does not exist"
fi
Using getent uses the standard C library for directory lookups. Thus, it's good for not only /etc/passwd, /etc/group, etc., but also directory services such as Active Directory, LDAP, NIS, YP and the like.
Here's what you do:
Search for a group name
Input the group name to search for
Sadly, you can't search for the group name before you input it, as this would violate causality and the laws of spacetime as we know them. Try searching after you know what you search for instead:
echo -n "Please enter the group name that you would like to search for..press [ENTER] when done: " # Request User input to obtain group name
read group
if cat /etc/group | grep -q "^$group:"
then
echo "The group already exist. Nothing more to do buddy."
fi

Resources