While loop in BASH script causing syntax error - bash

I recently started writing BASH scripts, and I am currently trying to practice using while loops. However, when I run the following block of code, the command prompt responds with:
run.command: line 12: syntax error near unexpected token `done'
run.command: `done'
Then the program shuts off.
This is the code I am running.
#!/bin/bash
echo -e "text"
c=false
while true; do
printf ">> "
i=read
if [$i = "exit"]; then
exit
else if [$i = "no"]; then
echo "no"
else
echo -e "Error: $i is undefined"
fi
done
I did some research on while loops, however my loop syntax seems correct. When I remove the done at the end, and Unexpected end of file error occurs. Any help would be appreciated!

You can use the -p option of read for the prompt and a case ... esac construction:
while true; do
read -r -p ">> " i
case "$i" in
"exit") exit 0 ;;
"no") echo "no" ;;
*) echo -e "Error: $i is undefined";;
esac
done

I fixed it myself!
#!/bin/bash
echo -e "text"
c=false
while true; do
printf ">> "
read i
if [ "$i" = "exit" ]; then
exit
elif [ "$i" = "no" ]; then
echo "no"
else
echo -e "Error: $i is undefined"
fi
done

Related

Terminate shell script after three invalid input

Restricting user from trying multiple invalid attempt in shell scripting. I wrote the below script but somehow it's not getting me desire output. I have shared the script and script output both. Kindly help. Here I wanted script to terminate if user tried more than 3 times.
While true
do
echo -n "Enter yes or no"
read opt
case $opt in
yes) break ;;
no) break ;;
*) echo "Invalid input"
while [[ $err -le 3 ]]
do
If [[ $err -le 3 ]]
then
echo "err: $err"
((err++))
break
else
echo "Max limit crossed"
exit 1
fi
done
;;
esac
done
This was a nice question and I had a lot of fun solving it. I have to mention that I'm new to shell programming.
n=0
until [ $n -ge 3 ]
do
read line
if [ "$line" = "XYZ" ]; then
echo "Accepted"
break
else
n=$[$n+1]
echo " trying " $n "times "
fi;
done
This article helped me a lot to solve it.
Try:
#!/bin/bash
ANSWER=
max=3
while true; do
echo "Enter yes or no:"
read -r ANSWER
[[ $ANSWER == "yes" || $ANSWER == "no" ]] && break
echo Invalid Input
ANSWER=
((--max))
[[ $max -le 0 ]] && { echo "Max limit crossed"; exit 1; }
done

How to fix Bash script errors

I wrote a little Bash script called cs210_list.sh, and it is giving me the following errors when i run it either as bash cs210_list.sh or as
sh cs210_list.sh in linux:
cs210_list.sh: line 2: [0: command not found
cs210_list.sh: line 21: syntax error near unexpected token `fi'
cs210_list.sh: line 21: ` fi'
this is my very first bash script ever. I can't figure why I'm getting the errors. BTW, "(line 21)" is not actually in my code, it's just there for your reference.
$? -eq 0 This command is supposed to determine if there as a argument
#!/bin/bash
if [$? -eq 0];
then
echo "Error: Missing argument";
exit 1
fi
if [-e "$1"];
then
if [-d "$1"];
then
for i in $(ls)
do
if [-d "$i"];
then
echo "File: $i"
echo ""
else
echo "File: $i"
echo " Size: " $(stat -c%s $i)
fi
fi (line 21)
else
echo "$Error: File doesn't exist"
fi
done

getting error when running my bash script

I made this bash script but getting this error when running it: ./admin2.sh: line 78: syntax error near unexpected token else'
./admin2.sh: line 78:else'.
I've edited it many times but i cant seem to find what exactly the error is. this is the script:
#!/bin/bash
if [[ $key == 1029127 ]]
clear
echo -e ""
echo -e -n "${LIGHTRED}[!] ${WHITE}Loading admin menu"
spinner () {
local SP_WIDTH="$3"
local SP_DELAY="$4"
local SP_STRING=${2:-"'|/=\'"}
local SP_COLOR=0
tput civis
while [ -d /proc/$1 ]; do
((RANDOM%2 == 0)) && SP_COLOR=3$((RANDOM%8)) ||
SP_COLOR=9$((RANDOM%8))
printf "\e[1;${SP_COLOR}m\e7 %${SP_WIDTH}s \e8\e[0m" "$SP_STRING"
sleep ${SP_DELAY:-.2}
SP_STRING=${SP_STRING#"${SP_STRING%?}"}${SP_STRING%?}
done
tput cnorm
}
sleep 2.5 &
spinner "$!" '-\\|/' '1.1' '.2'
tput civis
sleep 1
tput cnorm
while true
do
clear
echo -e "${LIGHTCYAN} Welcome"
echo -e ""
echo -e -n "${WHITE}- Current IP:${LIGHTRED} "
w|awk '{if(NR>2){print $3}}' $3
echo -e -n "${WHITE}- Users connected:${LIGHTRED} "
users | wc -w
echo -e "${WHITE}- Admin privileges:${WHITE
[${LIGHTGREEN}Enabled${WHITE}]"
echo -e ""
echo -e "${LIGHTRED} //Announcements//"
echo -e ""
echo -e "${YELLOW}- Type: /help to see commands"
echo -e "\n"
echo -e ""
echo -e ""
echo -e -n "${LIGHTRED}Type: \c"
read answer
else
echo -e ""
echo -e "${LIGHTRED}[!] ${WHITE}Incorrect key, access denied.
fi
You also seem to have forgotten to end the second while loop. You should end it by adding a doneon the line before the else
...
read answer
done
else
echo -e ""
echo -e "${LIGHTRED}[!] ${WHITE}Incorrect key, access denied.
fi
You're missing a then after your if statement on line 2:
if [[ $key == 1029127 ]]
then
...
else
...
fi
Many people prefer to put the then on the same line, as:
if [[ $key == 1029127 ]]; then
...
else
...
fi
Either way I'd encourage you to properly indent your code so that it's easier to read, and be consistent about style choices such as putting then and do on separate lines or not.

What's Wrong With My Bash Script? (line 43: syntax error near unexpected token `elif')

I've following a Lynda.com course online.
I'm trying to learn all I can but I still struggle with Command Substitution, Arrays and a If loops sometimes.
#!/bin/bash
MLOG="/var/log/mail.log"
SLOG="/var/log/syslog"
echo "Which log(s) do you want to see? "
echo "[1] Head Of Mail.log?"
echo "[2] Head Of Syslog?"
echo "[3] Tail Of Mail.log?"
echo "[4] Tail Of Syslog?"
echo "[5] Dump Mail.log to File?"
echo "[6] Dump Syslog to File?"
read -p "Select an option [1-6]: " OPTION
if
test "$OPTION" -eq "1"
then
head $MLOG
elif
test "$OPTION" -eq "2"
then
head $SLOG
elif
test "$OPTION" -eq "3"
tail $MLOG
elif
test "$OPTION" -eq "4"
tail $SLOG
elif
test "$OPTION" -eq "5"
cat "$MLOG" > ./MessageLogDump.txt
echo "Message.Log Successfully Dumped in PWD"
elif
test "$OPTION" -eq "6"
cat "$SLOG" > ./SysLog.txt
echo "Syslog Successfully Dumped in PWD"
else $? -ne "0"
echo "Something went wrong somewhere"
else z $OPTION
echo "You selected an incorrect option"
fi
There Error I receive on any output: Even with just STDIN of "1"
./GenSysLog.sh: line 43: syntax error near unexpected token `elif'
./GenSysLog.sh: line 43: ` elif'
I've tried searching other questions and answers on here with the same error, and I noticed people mentioning about CR & LF but I still can't figure it out.
Thank you.
Don't use upper-case variable names except for environment variables and built-in shell variables -- doing that increases your risk of namespace collisions. Beyond that, consider a case statement:
error() { echo "Something went wrong somewhere"; }
trap error ERR
read -p "Select an option [1-6]: " option
case $option in
1) head "$MLOG" ;;
2) head "$SLOG" ;;
3) tail "$MLOG" ;;
4) tail "$SLOG" ;;
5) cat "$MLOG" > ./MessageLogDump.txt
echo "Message.Log Successfully Dumped in PWD" ;;
6) cat "$SLOG" > ./SysLog.txt
echo "Syslog Successfully Dumped in PWD";;
*) echo "You selected an incorrect option" ;;
esac
Much shorter and easy to read.

Weird behavior using the read command in a infinite loop

I have a script that checks if a file exists or not using the ls command. If there is not a file I ask the user if he would like to continue with the script.
What I am finding is that the read command excepts input from the terminal instead of the keyboard?
Here is my script:
function isfileThere(){
output=$(ls ${1} 2>&1 >/dev/null)
case $output in
*"No such file or directory"*)
echo "DS not found: $output";
option_exitprog; $output >> DSNotFound.txt ;;
*) echo "DS found: $output";;
esac
}
function option_exitprog(){
while :
do
echo -n "Would you like to continue (y/n)?"
read Answer
#read -n1 -p "Would you like to continue (y/n)?" Answer
if [ ! -z "$Answer" ] ; then
if [ "$Answer" == "y" ] ; then
echo "Exiting script. Goodbye"
exit 1
elif [ "$Answer" == "n" ] ; then
echo "Continue With Program"
break
else
echo "We only accept (y/n)"
fi
else
echo "You have entered a null string. We only accept (y/n)"
fi
done
}
function get_TotalEventEntries(){
cat<<EOF
####################################
# #
# #
# get Total Entries #
# #
# #
####################################
EOF
while read LINE
do
let total_DSNumber=total_DSNumber+1
#Check if files exist
isfileThere ${FileDir}/*${LINE}*/*.root*
#print to file
#printf "${LINE}=" >> ${Filename}
#getEntries ${LINE} >> ${Filename}
done < ${DSWildCardFile}
echo "Finished running over $total_DSNumber file(s)"
}
get_TotalEventEntries
The problem is at this line: done < ${DSWildCardFile}. You cannot read lines from this file and read user at the same time with read and simple redirection . To fix it, use more complex redirection and a new file descriptor:
while read -u 3 LINE
do
...
done 3< ${DSWildCardFile}

Resources