This question already has answers here:
When are square brackets required in a Bash if statement?
(3 answers)
Closed 1 year ago.
I'm fairly new to Linux and I'm working my way though a course of learning. I've been working on a script to create a new group, which checks for duplicates and then also does the same for a new user and configures some parameters for the user. I've gotten so far, but I suspect, I'm either over-complicating it, or just too much of a noob.
Here's my script:
#!/bin/bash
# Challenge Lab B: Bash Scripting
# Script settings in OS:
# 1. set user owner to root
# 2. set group owner to root
# 3. set permission to include setuid (4755)
# 4. run script with sudo
echo -n 'Enter new group: '
read group_name
echo 'checking for duplicates...'
while [ grep -q "$group_name" /etc/group == 0 ]
do
echo 'group already exists; try another.'
if [ grep -q "$group_name" /etc/group == 1 ];
then
break
fi
done
echo 'group does not exist.';
echo 'creating group.';
groupadd $group_name;
echo "$group_name group created";
echo -n 'Enter new user: '
read user_name
while [ grep -q "$user_name" /etc/passwd == 0 ]
do
echo 'user already exists; try another.'
if [ grep -q "$user_name" /etc/passwd == 1 ];
then
break
fi
done
echo 'user does not exist.';
echo 'creating user directory.';
mkdir /$user_name;
echo 'creating user.';
useradd -s /bin/bash -g $group_name $user_name;
echo "changing home directory user and group ownership to $user_name";
chown $user_name:$group_name /$user_name;
echo 'changing user and group mode to RWX and setting sticky bit';
chmod 1770 /$user_name
echo "Process complete"
And here's the result:
Enter new group: test1
checking for duplicates...
./test_sc: line 25: [: too many arguments
group does not exist.
creating group.
test1 group created
Enter new user: user1
./test_sc: line 57: [: too many arguments
user does not exist.
creating user directory.
creating user.
changing home directory user and group ownership to user1
changing user and group mode to RWX and setting sticky bit
Process complete
Clearly, it kind of works, but I'm sure the low-level handling of the duplicate isn't working based upon the result.
I'm sure many will look upon my work as terrible, but this is my first one, so please bear that in mind.
Cheers,
S
if [ grep -q "$user_name" /etc/passwd == 1 ];
The brackets are not just syntax: [ is a command.
Take note of the if syntax:
$ help if
if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi
Execute commands based on conditional.
...
The part you put after if is a command. if branches based on the exit status of the command.
You want
if ! grep -q "$user_name" /etc/passwd; then
You should remove square brackets this way if you want to check return value (true or false):
while [ grep -q "$group_name" /etc/group == 0 ]
change to:
while grep -q "$group_name" /etc/group; do
If you want to check that this value is incorrect, add ! before the command
You should do that not only for while loops, but also for if statements
Or if you want to check return value for a specific value, let's say 15:
grep something file
ret=$(echo $?)
if [ $ret == 15 ]; then
do something;
fi
$? will return the last return value from the command that you have executed in bash
Related
apps="http:git.abc.com";
cluster-ui="http:git.xyz.com";
customer-ui="http:git.xxx.com";
SERVICE=$1;
My requirement is if I pass service name as a 'apps' then I need to clone the $apps url.
Here
if [ $Service -eq apps ]
not think a good approach as my repo url might get increased so more and more loop will come
Any suggestions?
The $ sign assigns the input argument, so we're getting first input if it matches the below variable, so do what you want inside if condition.
#!/bin/bash
apps="http:git.abc.com";
clusterui="http:git.xyz.com";
customerui="http:git.xxx.com";
#SERVICE=$1;
#Store global
repo=''
# if empty parameter is passed
if [ $# -lt 1 ] ; then
echo "Parameters Need"
exit 1
fi;
# for search the correct parameter
if [ $1 = "apps" ]; then
repo=$apps
elif [ $1 = "cluster-ui" ] ; then
repo=$clusterui
elif [ $1 = "customer-ui" ] ; then
repo=$customerui
else
echo "Not found"
fi;
echo $repo
Note just repeat elif [ ] ;then for more entries or think!
how to access run this file like this sh ./file.sh apps just replace apps with yours. make sure you have permission to execute the file if you don't have, give it to permission like below
chmod 766 file
now run the shell script sh ./file.sh clusterui
'Case statement' would suit here more than if ladder
I am a beginner and trying to write a script that takes a config file (example below) and sets the rights for the users, if that user or group doesn´t exist, they get added.
For every line in the file, I am cutting out the user or the group and check if they exist.
Right now I only check for users.
#!/bin/bash
function SetRights()
{
if [[ $# -eq 1 && -f $1 ]]
then
for line in $1
do
var1=$(cut -d: -f2 $line)
var2=$(cat /etc/passwd | grep $var1 | wc -l)
if [[ $var2 -eq 0 ]]
then
sudo useradd $var1
else
setfacl -m $line
fi
done
else
echo Enter the correct path of the configuration file.
fi
}
SetRights $1
The config file looks like this:
u:TestUser:- /home/temp
g:TestGroup:rw /home/temp/testFolder
u:TestUser2:r /home/temp/1234.txt
The output:
grep: TestGroup: No such file or directory
grep: TestUser: No such file or directory
"The useradd help menu"
If you could give me a hint what I should look for in my research, I would be very grateful.
Is it possible to reset var1 and var2? Using unset didn´t work for me and I couldn´t find variables could only be set once.
It's not clear how you are looping over the contents of the file -- if $1 contains the file name, you should not be seeing the errors you report.
But anyway, here is a refactored version which hopefully avoids your problems.
# Avoid Bash-only syntax for function definition
SetRights() {
# Indent function body
# Properly quote "$1"
if [[ $# -eq 1 && -f "$1" ]]
then
# Read lines in file
while read -r acl file
do
# Parse out user
user=${acl#*:}
user=${user%:*}
# Avoid useless use of cat
# Anchor regex correctly
if ! grep -q "^$user:" /etc/passwd
then
# Quote user
sudo useradd "$user"
else
setfacl -m "$acl" "$file"
fi
done <"$1"
else
# Error message to stderr
echo Enter the correct path of the configuration file. >&2
# Signal failure to the caller
return 1
fi
}
# Properly quote argument
SetRights "$1"
I have been trying to make a shell script in bash that will display the following:
You are the super user (When I run the script as root).
You are the user: "user" (When I run the script as a user).
#!/bin/bash/
if { whoami | grep "root" }; then
echo $USER1
else
echo $USER2
fi
I keep recieving these syntax error messages:
script.sh: line 2: syntax error near unexpected token `then'
script.sh: line 2: `if { whoami | grep "root" }; then'
Could someone help me out?
If braces are used to chain commands then the last command must have a command separator after it.
{ foo ; bar ; }
userType="$(whoami)"
if [ "$userType" = "root" ]; then
echo "$USER1"
else
echo "$USER2"
fi
pay attention with your first line, the correct syntax for she-bang is:
#!/bin/bash
everything you put there, is the interpreter of your script, you can also put something like #!/usr/bin/python for python scripts, but your question is about the if statement, so you can do this in two ways in shell script using
if [ test ] ; then doSomething(); fi
or
if (( test )) ; then doSomething(); fi
so to answer your question basically you need to do this
#!/bin/bash
if [ `id -u` -eq 0 ] ; then
echo "you are root sir";
else
echo "you are a normal user"
fi
if (( "$USER" = "root" )); then
echo "you are root sir";
else
echo "you are a normal user"
fi
note that you could use a command using `cmd` or $(cmd) and compare using -eq (equal) or = (same), hope this help you :-)
I have a shell script where I pass (2) parameters, one to pass a dbname, the other to call one of (2) filenames. I want to check if either filename exists, then proceed with calling that script, else exit because the user can enter the wrong string and construct my_foo.sql which I don't want. I don't think I have the condition for setting "or" correctly since putting the correct param still produces error. Is there a better way to write this?
Here is what I have so far.
#/usr/bin/ksh
if [ $# != 2 ]; then
echo "Usage: test.sh <dbname> <test|live>" 2>&1
exit 1
fi
# Check actual file name
CHKSCRIPT1=/tmp/my_test.sql;
CHKSCRIPT2=/tmp/my_live.sql;
if [ -f "CHKSCRIPT1" ] || [ -f "CHKSCRIPT2" ]
then
/bin/sqlplus -s foo/bar #/my_$2.sql
else
echo "Correct sql script does not exist. Enter test or live"
exit 1
fi
Your issue is that you're not referencing your variables correctly:
if [ -f "$CHKSCRIPT1" ] || [ -f "$CHKSCRIPT2" ]
...
fi
edit: Per #chepner, you shouldn't use -o
In addition to the problem you had with expanding the parameters, you should separate what the user types from what files need to exist. If the user enters "live", the only thing that matters is whether or not /tmp/my_live.sql exists. If the user enters "injection_attack", your script should not execute /tmp/my_injection_attack.sql (which presumably was created without your knowledge). The right thing to do is to first verify that a valid command was entered, then check if the appropriate file exists.
if [ $# != 2 ]; then
echo "Usage: test.sh <dbname> <test|live>" 2>&1
exit 1
fi
case $2 in
test|live)
filename="/tmp/my_{$2}.sql"
;;
*) echo "Must enter test or live"
exit 1
;;
esac
if [ -f "$filename" ]; then
/bin/sqlplus -s foo/bar #/my_$2.sql
else
echo "SQL script $filename does not exist."
exit 1
fi
This shell script is supposed to add users to the system. The new users details are in a file. The shell is rejecting this script with the message:
syntax error near unexpected token 'done'.
What's wrong?
#!/bin/bash
#Purpose: Automatically add new users in a linux system based upon the data found within a text file
# Assign encryped passwords to each user
# Add users to groups or create new groups for these users
# Report errors and successful operations where necessary in log files
# post help options (echo)
#Root validation
if [[ $(id -u) -eq 0 ]]; then
#Argument validation
if [[ -z "$1" ]]; then
echo "No arguments found!"
echo "Please include a user detail text file as first argument"
echo "Please include a report text file as second argument"
echo "Please include an error report text file as the third argument"
echo "Use the -h argument (i.e. ./script -h) for help"
exit 1
fi
#Help validation and Help file
if [[ "$1" = "-h" ]]; then
echo "This is the help information file"
echo "This script is designed to add users to a linux system by reading information from a user detail file (such as userlist.txt)"
echo "The format of this user detail text file is "username password groupname fullname" seperated using TAB spacing"
echo "This script will read the first argument as the user detail file, the second and third arguments will be read as a success report file and error report file respectively"
exit
fi
#Reads first argument as user detail file for data
cat userlist.txt | while read uname password gname fullname
#Reads /etc/passwd for Username
egrep -w "^$uname" /etc/passwd
#If Username is found then error reports
if [ $? == 0 ]; then
echo "User Already Exists : Error adding user with username $uname;$gname;$fullname" >> Successes1.log
exit 1
else
#Reads /etc/group for Groupname
egrep -w "^$gname" /etc/group
#If Groupname is found then nothing
if [ $? == 0 ]; then
echo ""
else
#If Groupname not found then creates new group and reports
groupadd "$gname"
echo "Group Not Found: New Group $gname was created" >> Successes1.log
fi
#Retrieves Date
createddate=$(date)
#Perl password script takes input from Userlist
pass=$(perl -e 'print crypt($ARGV[0], "Password")' "$password")
#Adds Users with variables from userlist
useradd "$uname" -g "$gname" -c "$fullname" -p "$pass"
#Reports information to successlist and errorlist report files
if [ $? == 0 ]; then
groupid=$(id -g $uname)
userid=$(id -u $uname)
echo "User Successfully Added: $uname;$userid;$gname;$groupid;$createddate;$fullname" >> Successes1.log
else
groupid=$(id -g $uname)
userid=$(id -u $uname)
echo "Useradd Error Occurred: $uname;$userid;$gname;$groupid;$createddate;$fullname" >> Errors1.log
echo "Error: Must be root user to execute script"
exit
fi
done
Second attempt
Using some of the ideas from the answers, I came up with a second attempt:
#!/bin/bash
#Purpose: Automatically add new users in a linux system based upon the data found within a text file
# Assign encryped passwords to each user
# Add users to groups or create new groups for these users
# Report errors and successful operations where necessary in log files
# post help options (echo)
#Root validation
if [[ $(id -u) -eq 0 ]]; then
#Argument validation
if [[ -z "$1" ]]; then
echo "Usage: $0 usernames report errors" 1>&2
echo "Please include a user detail text file as first argument"
echo "Please include a report text file as second argument"
echo "Please include an error report text file as the third argument"
echo "Use the -h argument (i.e. ./script -h) for help"
exit 1
fi
fi
#Help validation and Help file
if [[ "$1" = "-h" ]]; then
echo "This is the help information file"
echo "This script is designed to add users to a linux system by reading information from a user detail file (such as userlist.txt)"
echo "The format of this user detail text file is "username password groupname fullname" seperated using TAB spacing"
echo "This script will read the first argument as the user detail file, the second and third arguments will be read as a success report file and error report file respectively"
exit
fi
#Reads first argument as user detail file for data
cat jan.txt | while read uname password gname fullname; do
#Reads /etc/passwd for Username
egrep -w "^$uname:" /etc/passwd >/dev/null 2>&1
#If Username is found then error reports
if [ $? == 0 ]
then
echo "User Already Exists : Error adding user with username $uname;$gname;$fullname" >> Errors1.log
else
#Reads /etc/group for Groupname
egrep -w "^$gname" /etc/group
#If Groupname is found then nothing
if [ $? == 0 ]; then
echo ""
else
#If Groupname not found then creates new group and reports
groupadd "$gname"
echo "Group Not Found: New Group $gname was created" >> Successes1.log
done < $1
#Retrieves Date
createddate=$(date)
#Perl password script takes input from Userlist
pass=$(perl -e 'print crypt($ARGV[0], "Password")' "$password")
#Adds Users with variables from userlist
useradd "$uname" -g "$gname" -c "$fullname" -p "$pass"
#Reports information to successlist and errorlist report files
if [ $? == 0 ]
then
groupid=$(id -g $uname)
userid=$(id -u $uname)
echo "User Successfully Added: $uname;$userid;$gname;$groupid;$createddate;$fullname" >> Successes1.log
else
groupid=$(id -g $uname)
userid=$(id -u $uname)
echo "Useradd Error Occurred: $uname;$userid;$gname;$groupid;$createddate;$fullname" >> Errors1.log
echo "Error: Must be root user to execute script"
exit 1
fi
fi
done
This does not seem to work properly either. What's wrong now?
Seems to show arguments and runs however no users nor group have been added therefore no logs have been created
The if starting at:
if [ $? == 0 ]; then
echo "User Already Exists : Error adding user with username ...
exit 1
else
is ended with the done instead of the fi that is required.
The while loop starting a couple of lines earlier:
cat userlist.txt | while read uname password gname fullname
is missing its do (another bug); if that was present, then it would also need the done at the end. Someone lost track of the indentation. (Using 2 characters per level is better than 0 or 1, but it is easier to track levels if you use 4 spaces per level.) Note that the shell hasn't gotten around to complaining about the lack of do because the syntax for a while loop is:
while cmd1
cmd2
cmd3 ...
do
and as far as the shell is concerned, it is still processing commands in the list cmd1, cmd2, cmd3, ....
Here's a semi-decently indented version of the script. There was a missing fi at the top of the script, too.
#!/bin/bash
#Purpose: Automatically add new users in a linux system based upon the data found within a text file
# Assign encryped passwords to each user
# Add users to groups or create new groups for these users
# Report errors and successful operations where necessary in log files
# post help options (echo)
#Root validation
if [[ $(id -u) -eq 0 ]]
then
#Argument validation
if [[ -z "$1" ]]
then
echo "No arguments found!"
echo "Please include a user detail text file as first argument"
echo "Please include a report text file as second argument"
echo "Please include an error report text file as the third argument"
echo "Use the -h argument (i.e. ./script -h) for help"
exit 1
fi
fi
#Help validation and Help file
if [[ "$1" = "-h" ]]
then
echo "This is the help information file"
echo "This script is designed to add users to a linux system by reading information from a user detail file (such as userlist.txt)"
echo "The format of this user detail text file is "username password groupname fullname" seperated using TAB spacing"
echo "This script will read the first argument as the user detail file, the second and third arguments will be read as a success report file and error report file respectively"
exit
fi
#Reads first argument as user detail file for data
cat userlist.txt | while read uname password gname fullname
do
#Reads /etc/passwd for Username
egrep -w "^$uname" /etc/passwd
#If Username is found then error reports
if [ $? == 0 ]
then
echo "User Already Exists : Error adding user with username $uname;$gname;$fullname" >> Successes1.log
exit 1
else
#Reads /etc/group for Groupname
egrep -w "^$gname" /etc/group
#If Groupname is found then nothing
if [ $? == 0 ]
then
echo ""
else
#If Groupname not found then creates new group and reports
groupadd "$gname"
echo "Group Not Found: New Group $gname was created" >> Successes1.log
fi
#Retrieves Date
createddate=$(date)
#Perl password script takes input from Userlist
pass=$(perl -e 'print crypt($ARGV[0], "Password")' $pass)
#Adds Users with variables from userlist
useradd "$uname" -g "$gname" -c "$fullname" -p "$pass"
#Reports information to successlist and errorlist report files
if [ $? == 0 ]
then
groupid=$(id -g $uname)
userid=$(id -u $uname)
echo "User Successfully Added: $uname;$userid;$gname;$groupid;$createddate;$fullname" >> Successes1.log
else
groupid=$(id -g $uname)
userid=$(id -u $uname)
echo "Useradd Error Occurred: $uname;$userid;$gname;$groupid;$createddate;$fullname" >> Errors1.log
echo "Error: Must be root user to execute script"
exit
fi
fi
done
There is still much room for improvement. The root validation block should exit if the user is not root; that happens instead a mile further down inside the loop. You can check the number of arguments better: $# gives you the number of arguments. If I tried yourscript.sh '' arg2 arg3, you'd claim there were no arguments when in fact the problem is that $1 is present but is an empty string. The standard convention for reporting how to use a command is something like:
echo "Usage: $0 usernames report errors" 1>&2
This reports the command's name, and the arguments expected. The 1>&2 sends the message to standard error instead of standard output. The logic here is a little bizarre even so. You check that the user is root and only then check that there are arguments. If the user is not root, you don't check the arguments. Not entirely sensible, I submit.
We can debate the UUOC (Useless Use of Cat). There's actually an award for it; I don't think this qualifies. However, it would be possible to write:
while read uname password gname fullname
do
...
done < $1
Hmmm...the script is supposed to take a file name argument that specifies the users, but the cat takes a fixed file name, not the file name argument!
Similarly, arguments 2 and 3 are studiously ignored; the log files are hard-coded.
egrep -w "^$uname" /etc/passwd
#If Username is found then error reports
if [ $? == 0 ]
This fragment can be improved several ways:
if egrep -w "^$uname:" /etc/passwd >/dev/null 2>&1
then
#If Username is found then error report
This tests the exit status of the egrep command directly; it also prevents a new user roo from being treated as pre-existing because of user root. It sends the output and error output to /dev/null so that you won't see anything when the user does exist.
It might be better not to exit when the user name is found; you could at least try to process the next entry. It is also odd that the report that the user exists (which terminates the processing) is recorded in Successes1.log rather than in Errors1.log; it is treated like an error.
The group check constructs are similar and should be similarly upgraded.
You read the password into $password with the read line; when it comes to creating the password, though, you have:
pass=$(perl -e 'print crypt($ARGV[0], "Password")' $pass)
On the first cycle, $pass is empty (most probably); you should have used $password in double quotes at the end:
pass=$(perl -e 'print crypt($ARGV[0], "Password")' "$password")
As with the egrep commands, you can check the status of the useradd command directly too. It is a bit sweeping to say if [ $? == 0 ] is the mark of a tyro, but it isn't too far off the truth.
The final exit in the script should be exit 1 to indicate an error exit. As already noted, this is preceded by the comment about 'you must be root', even though there was a check at the top for root privileges.
Caveat: I've not attempted to run the script; I could easily have missed some issues. It does, however, pass sh -v -n, so there are no gross syntactic errors left.
Once a shell script is syntactically correct, then you normally debug it using sh -x script (or, if it takes arguments, then sh -x script arg1 arg2 arg3 ...). This is the execution trace mode. The shell tells you, more or less inscrutably, what it is doing. The information is written to standard error. You can even trap the output for later scrutiny if you like with:
sh -x script arg1 arg2 arg3 2>script-x.log
The 2>script-x.log notation sends the standard error to the file script-x.log (choose your own meaningful name; I often use x or xxx for files I won't want to keep, but I also remove such files without necessarily even looking at them because I know they are throwaway files).
"done" is supposed to be paired with a previous "do"
It does not man th end of your script.
Your while is missing a do:
cat userlist.txt | while read uname password gname fullname
do
or
cat userlist.txt | while read uname password gname fullname; do