Issue with shell if statement - bash

I have a shell script as follows (taken from some lecture slides):
#/bin/sh
echo -e "enter a number:\c"
read number
if [$number -ne 2]
then
echo "Number is not equals to 2"
fi
And I'm getting a syntax error where fi is. Any idea what the problem is?
Also, what does the extra term in echo -e "enter a number:\c" means (asides from the simple fact that it asks for a number)?
EDIT: now I did
#/bin/sh
echo -e "enter a number:\c"
read number
if [ "$number" -ne 2 ]
then
echo "Number is not equals to 2"
fi
And I'm still getting the error...
Same goes for
#/bin/sh
read -p "enter a number: " number
if [ "$number" -ne 2 ]
then
echo "Number is not equals to 2"
fi
SOLVED: I've made a copying error there. Thanks for the input by the way, guys.

Problem is this if condition:
if [$number -ne 2]
You need to put space after [ and before ] so use:
if [ "$number" -ne 2 ]
Your script can be rewritten as:
#/bin/sh
read -p "enter a number: " number
if [ "$number" -ne 2 ]
then
echo "Number is not equals to 2"
fi
However if bash is available then better to switch to bash instead of old bourne shell.

Related

Bash script syntax error: unexpected end of file [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
im trying to create a simple bash script to create and delete a user on ubunutu , here is my script
sudo nano createuser.sh
#!/bin/bash
choice=2
# Main Display
echo "Enter Number to select an option"
echo
echo "1) Add User"
echo "2) Delete User"
echo
while [ $choice -eq 2 ]; do
read choice
if [ $choice -eq 1] ;
then
echo -e "Enter Username"
read user_name
echo -e "Enter Password"
read user_passwd
sudo useradd $user_name -m -p $user_passwd
cat /etc/passwd
else if [$choise -eq 2] ; then
cat /etc/passwd
echo -e "Enter Password"
read del_passwd
echo -e "User to be deleted:"
read del_user
sudo userdel -r $del_user
cat /etc/passwd
echo
fi
im not sure if there s a typo on my script ,or something else .
whenever i execute the script i get this message
Enter Number to select an option
Add User
Delete User
./createuser.sh: line 31: syntax error: unexpected end of file
thank you in advance for your help !!
Errors:
wrong if/else/fi sequence, what you have is basically this w few errors
if [ ]
then
# something
else
if [ ]
then
# something else
fi
# fi should be here ti close outer if []
In bash you have if then/elif/else closed by fi So something like this
if []
then
# something
elif []
then
# something else happened
else
# something else than elif happened
fi
; after if [], it only goes there if if and than are in the same line, like so
if [] ; then
# something
elif []
# something else happened
else
# something else than elif happened
fi
space inside test brackets []
if [ a -eq 5 ]
# ^ ^
# +-------+----< notice space here
In bash while sequence goes as following while [ ] do done. like following
while [ i -le 55 ]
do
# do something
done
Suggestions
use -s for reading in password in bash to hide it while typing.
Conclusion, with all the fixes above here is working script:
#!/bin/bash
choice=2
# Main Display
echo "Enter Number to select an option"
echo
echo "1) Add User"
echo "2) Delete User"
echo
while [ $choice -eq 2 ]
do
read choice
if [ $choice -eq 1 ]
then
echo -e "Enter Username"
read user_name
echo -e "Enter Password"
read user_passwd
sudo useradd $user_name -m -p $user_passwd
cat /etc/passwd
elif [ $choise -eq 2 ]
then
cat /etc/passwd
echo -e "Enter Password"
read del_passwd
echo -e "User to be deleted:"
read del_user
sudo userdel -r $del_user
cat /etc/passwd
echo
else
echo "Wrong option you have 1 or 2"
fi
done
yes guys ,thank you so much for your help
i just fixed it
here is my working script now
#!/bin/bash
choice=2
# Main display echo "Enter number to select an option" echo echo "1) Add User" echo "2) Delete User" echo
while [[ "$choice" -eq 2 ]]; do
read choice
if [[ "$choice" -eq 1 ]] ; then
echo -e "Enter Username"
read user_name
echo -e "Enter Password"
read user_passwd
sudo useradd "$user_name" -m -p "$user_passwd"
cat /etc/passwd else
if [[ "$choice" -eq 2 ]] ; then
cat /etc/passwd
echo
echo -e "User to be deleted:"
read del_user
sudo userdel -r "$del_user"
cat /etc/passwd
echo
choice=2
fi
fi
done

How to Ask User for Confirmation: Shell

I am new to shell, and my code takes two arguments from the user. I would like to confirm their arguments before running the rest of the code. I would like a y for yes to prompt the code, and if they type n for no, then the code will ask again for new arguments
Pretty much, if i type anything when I am asked to confirm, the rest of the code runs anyways. I tried inserting the rest of the code after the first then statement, but that didn't work either. I have also checked my code with ShellCheck and it all appears to be legal syntax. Any advice?
#!/bin/bash
#user passes two arguments
echo "Enter source file name, and the number of copies: "
read -p "Your file name is $1 and the number of copies is $2. Press Y for yes N for no " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]
then
echo "cloning files...."
fi
#----------------------------------------REST OF CODE
DIR="."
function list_files()
{
if ! test -d "$1"
then echo "$1"; return;
fi
cd ... || $1
echo; echo "$(pwd)":; #Display Directory name
for i in *
do
if test -d "$i" #if dictionary
then
list_files "$i" #recursively list files
cd ..
else
echo "$i"; #Display File name
fi
done
}
if [ $# -eq 0 ]
then list_files .
exit 0
fi
for i in "$#*"
do
DIR=$1
list_files "$DIR"
shift 1 #To read next directory/file name
done
if [ ! -f "$1" ]
then
echo "File $1 does not exist"
exit 1
fi
for ((i=0; i<$2; i++))
do
cp "$1" "$1$i.txt"; #copies the file i amount of times, and creates new files with names that increment by 1
done
status=$?
if [ "$status" -eq 0 ]
then
echo 'File copied succeaful'
else
echo 'Problem copying'
fi
Moving the prompts into a while loop might help here. The loop will re-prompt for the values until the user confirms them. Upon confirmation, the target code will be executed and the break statement will terminate the loop.
while :
do
echo "Enter source file name:"
read source_file
echo "Number of copies"
read number_of_copies
echo "Your file name is $source_file and the number of copies is $number_of_copies."
read -p "Press Y for yes N for no " -n 1 -r
if [[ $REPLY =~ ^[Yy]$ ]]; then
echo "cloning files...."
break ### <<<---- terminate the loop
fi
echo ""
done
#----------------------------------------REST OF CODE

Syntax error near unexpected token `done' - Shell Scripting

#!/bin/sh
VAR2=0
while [ $VAR2 -eq 0 ]: do
echo "Please choose one of the following options:"
echo "1. List the current running processes"
echo "2. Check the available free memory"
echo "3. List the disks/partitions"
echo "4. Check for hardware (PCI)"
echo "5. Check for package installation"
echo "6. Create multiple files"
echo "7. Remove multiple files"
echo "8. List the contents of the current directory"
echo "0. Exit"
read VAR1
if [ $VAR1 -eq 0 ]; then
VAR2=2
fi
if [ $VAR1 -eq 1 ]; then
$(top)
fi
if [ $VAR1 -eq 2 ]; then
$(free)
fi
if [ $VAR1 -eq 3 ]; then
$(df)
fi
if [ $VAR1 -eq 4 ]; then
echo "Insert the name of the hardware that you want to search:" read VARHARD $(sudo lspci | grep $VARHARD)
fi
if [ $VAR1 -eq 5 ]; then
echo "Insert the name of the package that you want to search:" read VARPACK $(rpm -qa | grep VARPACK)
fi
if [ $VAR1 -eq 6 ]; then
echo "Insert the base name of the files:" read VARFILE echo "Insert the amount of files you want:" read VARNUMB $(touch $VARFILE{0001..000$VARNUMB})
fi
if [ $VAR1 -eq 7 ]; then
echo "Insert a string to delete all files that contain it:" read VARDEL $(find -type f -name '*$VARDEL*' -exec rm {} \;)
fi
if [ $VAR1 -eq 8 ]; then
$(ls -la)
fi
echo "Press any key and enter to continue... "
read teste
done
So, when I try to run the script "sh script.sh", it gives me an error that says "Syntax error near unexpected token `token'"
Can someone explain the error to me please? I'm new on scripting.
Thanks!
You have two problems in your code, the first is the invocation of subshells where is not due (using $() ) and the second is a typo at the line 26 (you have if instead of fi). The following corrected code works:
#!/bin/bash
VAR2=0
while [ $VAR2 -eq 0 ]; do
echo "Please choose one of the following options:"
echo "1. List the current running processes"
echo "2. Check the available free memory"
echo "3. List the disks/partitions"
echo "4. Check for hardware (PCI)"
echo "5. Check for package installation"
echo "6. Create multiple files"
echo "7. Remove multiple files"
echo "8. List the contents of the current directory"
echo "0. Exit"
read VAR1
if [ $VAR1 -eq 0 ]; then
VAR2=2
fi
if [ $VAR1 -eq 1 ]; then
top
fi
if [ $VAR1 -eq 2 ]; then
free
fi
if [ $VAR1 -eq 3 ]; then
df
fi
if [ $VAR1 -eq 4 ]; then
echo "Insert the name of the hardware that you want to search:"
read VARHARD
sudo lspci | grep $VARHARD
fi
if [ $VAR1 -eq 5 ]; then
echo "Insert the name of the package that you want to search:"
read VARPACK
rpm -qa | grep VARPACK
fi
if [ $VAR1 -eq 6 ]; then
echo "Insert the base name of the files:"
read VARFILE
echo "Insert the amount of files you want:"
read VARNUMB
touch $VARFILE{0001..000$VARNUMB
fi
if [ $VAR1 -eq 7 ]; then
echo "Insert a string to delete all files that contain it:"
read VARDEL
find -type f -name '*$VARDEL*' -exec rm {} \;
fi
if [ $VAR1 -eq 8 ]; then
ls -la
fi
echo "Press any key and enter to continue... "
read teste
done
Why are you using the syntax $(top)? That will execute top to completion (it may be long running, and never end), and then evaluate the output as a command and attempt to execute it. Most likely, the output of top is not valid shell syntax. I'm not sure exactly which command is generating the syntax error related to token, but that's probably the source of your error. Instead of $(top), just write top. Same for all the other instances of $() in the script.

if statement shell script error

Hello I don't know if this will be a duplicate , but I really don't see the error in this piece of code . It gives me an error at the then statement and I think there is no error .
I have putted comments on the two lines where the code breaks .
Here is the code:
#!/bin/bash
echo -n "Enter first value:"
read firstvar
echo -n "Enter second value:"
read secondvar
echo -n "Enter last value:"
read compvar
echo -n "Enter operation:"
read ops
counter=0
result=0
while [ $result -eq $compvar ]
do
if [ $ops -eq "+" ]
then result = $((firstvar+secondvar))
elif [ $ops -eq "-" ]
then result = $((firstvar-secondvar))
#elif[ $ops -eq "*" ]
#then result = $((firstvar\*secondvar))
#elif[ $ops -eq "/" ]
#then result = $((firstvar/secondvar))
else
echo "Input valid operation !!!"
fi
(($counter++))
done
Oh shoot , I m retarded . Missed the space between "elif" and the "[" .
You need to learn how to space and indent to have your code legible.
#!/bin/bash
echo -n "Enter first value:"; read firstvar
echo -n "Enter second value:"; read secondvar
echo -n "Enter last value:"; read compvar
echo -n "Enter operation:"; read ops
counter=0; result=0 #initialize variables
while [ $result -eq $compvar ]; do
if [ $ops = "+" ]; then
result = $((firstvar+secondvar))
elif [ $ops = "-" ]; then
result=$((firstvar-secondvar))
else
echo "Input valid operation !!!"
fi
((++counter))
done
Writing code is the same as writing literature. There are forms to use to make it easy for the reader (even if it's just you 6 months later) to follow. Your code above is confusing, and will bite you on the butt later. Add comments to.
The while loop is gratuitous and will do nothing-- the -eq should at least be -ne. The counter could be initialized as an integer to avoid problems that could arise, but it's also never used.

if [ `ls $op_file` ]; then is returning true even the file is not found

#!/bin/bash
echo "Enter the o/p file name"
read op_file
echo "Enter the count"
read count
echo "OP filename : "
echo $op_file
if [ `ls $op_file` ]; then
echo "O/P file found"
else
exit 0
fi
I'm trying to check whether the filename is existing or not.Have to proceed if the file is existing. Though the above code doesn't give me error. It prints O/P file found even though the file is not found by ls.
Your script can be refactored to this:
#!/bin/bash
read -p "Enter the o/p file name" op_file
read -p "Enter the count" count
echo "OP filename: $op_file"
if [ -f "$op_file" ]; then
echo "O/P file found"
else
exit 1
fi
Better to use -f "$file" check for checking existence of a file. Also see man test
Use the -e operator in your if, this checks the for existence of a file, so:
if [ -e $op_file ]; then
echo "O/P file found"
else
exit 0
fi

Resources