I'm extremely new to this, but can anyone tell me why when I run this, it doesn't show my echo's?
It accepts all my inputs, but say when I do the subtraction one it doesn't display
echo "$a - $b = $(($a-$b))"
It worked if I put an Exit after each case, but I would like it to keep going after it completes one input.
#!/bin/bash
while true; do
clear
cat <<EOF
Please Select:
Option 1. Quit
Option 2. Display Options Again
Option 3. Subtraction
Option 4. Division
Option 5. Who am I?
EOF
read -p "Enter selection [1-5] > "
case "$REPLY" in
1)
break
;;
2)
;;
3)
read -p "Enter the First Number: " a
read -p "Enter the Second Number: " b
echo "$a - $b = $(($a-$b))"
;;
4)
printf "Enter the First Number: "
read a
printf "Enter the Second Number: "
read b
echo "$a / $b = $(($a/$b))"
;;
5)
echo "My name is Michelle"
;;
*)
echo "Invalid entry."
;;
esac
done
echo "Program terminated."
Any help would be greatly appreciated.
Problem here is that the first command in the loop is clear. This removes the output immediately after it was displayed.
Related
This question already has answers here:
Why should there be spaces around '[' and ']' in Bash?
(5 answers)
Closed 2 years ago.
I am a beginner in bash scripting. and i look for similar questions but none gave me the results am looking for.
I want to create a shell that keep giving the user some options to choose from while the choice is not exit
Here is my code
choice=0
while [$choice!=4]
do
echo "please choose the operation you want!"
echo "1) Delete Data"
echo "2) Insert Data"
echo "3) Get Number of customers"
echo "4) Exit"
choice=$1
if [$choice=1]; then
echo "you have chosen to Delete Data"
elif [$choice=2]; then
echo "you have chosen to Insert Data"
elif [$choice=3]; then
echo "you have chosen to Get number of customers"
fi # EOF if
done
As you can see that i want my code to keep asking for the user options until the answer is not exit.
My Question is this code gives me an infinite loop.
Bash, ksh or zsh provides you with the select command that is exactly designed to present numbered options menu:
To get the usage of the select command, type help select in your bash terminal.
select: select NAME [in WORDS … ;] do COMMANDS; done
Select words from a list and execute commands.
The WORDS are expanded, generating a list of words. The set of expanded words is printed on the standard error, each preceded by a number. If in WORDS is not present, in "$#" is assumed. The PS3 prompt is then displayed and a line read from the standard input. If the line consists of the number corresponding to one of the displayed words, then NAME is set to that word. If the line is empty, WORDS and the prompt are redisplayed. If EOF is read, the command completes. Any other value read causes NAME to be set to null. The line read is saved in the variable REPLY. COMMANDS are executed after each selection until a break command is executed.
Exit Status:
Returns the status of the last command executed.
Here is an implementation of it with your selection menu:
#!/usr/bin/env bash
choices=('Delete Data' 'Insert Data' 'Get Number of customers' 'Exit')
PS3='Please choose the operation you want: '
select answer in "${choices[#]}"; do
case "$answer" in
"${choices[0]}")
echo 'You have chosen to Delete Data.'
;;
"${choices[1]}")
echo 'You have chosen to Insert Data.'
;;
"${choices[2]}")
echo 'You have chosen to Get number of customers.'
;;
"${choices[3]}")
echo 'You have chosen to Exit.'
break
;;
*)
printf 'Your answer %q is not a valid option!\n' "$REPLY"
;;
esac
done
unset PS3
Another implementation of the select command, using arguments rather than an array of choices:
#!/usr/bin/env ksh
PS3='Please choose the operation you want: '
set -- 'Delete Data' 'Insert Data' 'Get Number of customers' 'Exit'
select answer; do
case "$answer" in
"$1")
echo 'You have chosen to Delete Data.'
;;
"$2")
echo 'You have chosen to Insert Data.'
;;
"$3")
echo 'You have chosen to Get number of customers.'
;;
"$4")
echo 'You have chosen to Exit.'
break
;;
*)
printf 'Your answer %q is not a valid option!\n' "$REPLY"
;;
esac
done
If you want to use while loop with conditional 'case' syntax, try this:
while true
do
echo "1) Delete Data"
echo "2) Insert Data"
echo "3) Get Number of customers"
echo "4) Exit"
echo -ne "Enter your choice [0-4] > \c"
read choice
case "$choice" in
1) echo "you have chosen to Delete Data" ; break
;;
2) echo "you have chosen to Insert Data"; break
;;
3) echo "you have chosen to Get number of customers"; break
;;
4) exit
;;
*) clear
;;
esac
done
i found the error. it was statement typing issue not in the algorithm
my new code is
while [ "$(read choice)"!="4" ]
do
if [ "$choice"="1" ]; then
echo "you have chosen to Delete Data"
elif [ "$choice"="2" ]; then
echo "you have chosen to Insert Data"
elif [ "$choice"="3" ]; then
echo "you have chosen to Get number of customers"
fi # EOF if
echo "please choose the operation you want!"
echo "1) Delete Data"
echo "2) Insert Data"
echo "3) Get Number of customers"
echo "4) Exit"
done
I am writing a shell script (named "test-script.sh"). One feature is as below:
When I typing the script name in CLI and click <ENTER>, The script name will be keeped in CLI following with the cursor when an error encountered.
Such as:
me#ubuntu: $ test-script.sh <ENTER>
me#ubuntu: $ Sorry, you must input at least one parameter.
me#ubuntu: $ test-script.sh[cursor] <<<< Here the script name auto printed and following with the cursor.
Let's take echo ${!!d} as an example. When you run echo ${!!d} in CLI, an error will print but the cmd echo ${!!d} will hold in CLI.
Here echo is my test-script.sh.
How to achieve this feature in my script?
Thank you~
echo $0 will print the script name: $0 - is script name, $1 is 1st CL argument, $2 is 2nd CL argument and so on..., $# is number of argument.
Example:
output:
$ ./test_script.sh
Sorry, you must input at least one parameter.
here are the options:
1. for option one
2. for option two
3. for option three
./test_script.sh 1
do you stuff for option 1 here
$
Script:
#!/bin/sh
menu(){
echo "here are the options:"
echo "1. for option one"
echo "2. for option two"
echo "3. for option three"
}
if [ $# -eq 0 ];
then
echo "Sorry, you must input at least one parameter."
menu
read -p "$0 " option
else
option=$1
fi
case $option in
"1") echo "do you stuff for option 1 here" ;;
"2") echo "do you stuff for option 2 here" ;;
"3") echo "do you stuff for option 3 here" ;;
*)
echo
echo "Invalid option: ${option}"
echo "...exiting...";sleep 1
exit
;;
esac
So I have to make this little calculator in bash with some simple functions which you can see below in the code(which is the debug version). However during execution I'm having an issue where inputting * into operation2 is giving me [: too many arguments, this however does not occur with operation1.
I need the calculator to take this input for inputs like 1+1*2 etc as the script needs to keep going till the user enters "=" hence the while ! loop. I am new to batch scripting so I have no clue what I have to change. I know from debugging it is calling up a list of the files in the dictionary this script is located in, so I believe it must be misinterpreting the command.
The code is as follows with the issue happening when reading in * on either operation2. It works however for all the other inputs (+, -, /, =)
#bin/bash +x
begin=$(date +"%s")
echo "Please Enter Your Unix Username:"
read text
userdata=$(grep $text /etc/passwd | cut -d ":" -f1,5,6 | tr -d ',')
echo "The User: $userdata" >> calcusers.txt
date=$(date)
echo "Last Ran calculator.sh on: $date " >> calcusers.txt
echo "---------------------------------------------------------" >> calcusers.txt
name=$(grep $text /etc/passwd | cut -d ":" -f5 | cut -d\ -f1)
echo -n "Hello" $name && echo ", Welcome to calculator.sh."
echo "To begin using calculator.sh to do some calculations simply type a number"
echo "below, followed by the type of sum you want to perform and the input for"
echo "a second number, third and so on. To output the equation simply type =."
set -x
echo "Please Enter a Number:"
read number1
echo "Would you like to Add(+), Subtract(-), Multiply(*) or Divide(/) that number?"
read operation1
echo "Please Enter a Number:"
read number2
total=$(echo "$number1$operation1$number2" | bc)
echo "Would you like to Add(+), Subtract(-), Multiply(*), Divide(/) or Equals(=) that equation?"
read operation2
while [ ! $operation2 = "=" ]
do
echo "Please Enter a Number:"
read number3
total=$(echo "$total$operation2$number3" | bc)
echo "Would you like to Add(+), Subtract(-), Multiply(*), Divide(/) or Equals(=) that equation?"
read operation2
done
set +x
echo -n "The total of the equation is" $total && echo "."
termin=$(date +"%s")
difftimelps=$(($termin-$begin))
echo "Thanks for using calculator.sh!"
echo "$(($difftimelps / 60)) minutes and $(($difftimelps % 60)) seconds has passed since the Script was Executed."
exit 0
Quote your variables everywhere:
while [ ! "$operation2" = "=" ]
# ........^............^
Also, you should expect invalid input from your users
while [ ! "$operation2" = "=" ]
do
case "$operation2" in
[*/+-])
echo "Please Enter a Number:"
read number3
total=$(echo "$total$operation2$number3" | bc)
;;
*) echo "Invalid operation: '$operation2'"
;;
esac
echo "Would you like to Add(+), Subtract(-), Multiply(*), Divide(/) or Equals(=) that equation?"
read operation2
done
Bellow is my code for a shell script. I can't run it in a terminal. Could anyone tell me why this is?
#!/bin/bash
TIMELIMIT=500
#start="y"
while [["$start"!="n"]]
do
setterm-clear all
echo -en'\E[45;55m'"\033[1mcopyright reserved by Ali\033[Om"
echo " *********************************************************** "
#tput sgr0
#echo-e"\033[;10;40m"
echo "PLEASE INSERT YOUR CARD"
#tput sgr0
#echo-e"\033[45;41m"
echo "WELCOME TO BANK IT AUTOMATED TELLER MACHINE"
sleep 5
echo " Loading..."
#sleep 3
#id=id | awk -F[=(]' '{print $1 $1 $1 $1}'
#echo -e "\033[;10;40m"
echo-e "PLEASE KEY IN YOUR PASSWOED: \c"
#tput sgr0
read-t $TIMELIMIT userpassword
setterm-clear all
if [-z"$userpassowrd" ]
then
echo "YOU USE TOO LONG TIME, PLEASE TRY AGAIN"
sleep 3
./t3.sh
fi
#seeterm-clear all
echo "Loading..."
sleep 5
#setterm-clear all
sleep 3
idpassword="$userpassword"
grep-s "$idpassword" db
#Verify ID number with Password
if ["$?" = 1]
then
echo "INVALIDE PASSWORD! PLEASE TRY AGAIN."
sleep 3
./t3.sh
fi
setterm-clear all
nawk-F:'/'$idpassword'/{print $2}' db > db10
username= 'cat db10'
continue="y"
while [["$continue"!= "n"]]
do
echo "WELCOME TO USE BANK IT ATM, $username"
echo "Press 1 for Withdraw Money"
echo "Press 2 for Balance Checking"
echo "Press 3 for Logout"
echo "Please Press Your Service:"
#User no need press enter here.
read-s-t $TIMELIMIT-n1 service
if[-z"$service"]
done
echo Times out, please choose.
sleep 3
./t3.sh
done
setterm -clear all
case "$service" in
1)
#cat db2
#nawk -F:'/'*'/'$idpassword{print "lala"}' db
#nawk 'sub(/'$idpassword'/,"asas"){print}' db >> db2
awk '$1 !~/'$userpassword'/' db > db2
echo "Withdraw Money"
echo-e "Amount: RM\c"
read withdrawAmount # echo . > db4
nawk -F:'/'$idpassword'/{print $3}' db > db5
oldbalance = 'cat db5';
newbalance = 'echo $oldbalance - $withdrawAmount | bc-1'
newrecord = "$idpassword: $username: $newbalance"
echo $newrecord > db3
cat db3 >> db2
cp db2 db
#start inbound switch
echo "continue?y n"
read-s-n1 selection
case"$selection"in
;;
y)
setterm-clear all
continue="y" #dont put space, for example, goout="n"
;;
n)
setterm-clear all
echo Thank you
continue="n"
sleep 4
;;
esac
#end inbound switch
2)
nawk -F:'/'$idpassword'/{print " YOUR BALANCE IS: RM"$3}'db
#start inbound switch
echo "continue? y n"
#read-s-n1 selection
#case"$selection" in
y)
setterm-clear all
continue="y" #dont put space, for example, goout="n"
;;
n)
setterm-clear all
echo Thank you
continue="n"
sleep 4
;;
esac
#end inbound switch
;;
3)
setterm -clear all echo "THANK YOU FOR USING OUR SERVICE"
echo " *********************************************************** "
break
continue="n"
sleep 3
;;
esac
done
done
exit 0
#exit 0
#sleep 3000
;;
done
Like Mat said, you need to be more specific. However, I notice that this line:
while [["$start"!="n"]]
Should be
while [[ "$start"!="n" ]]
Meaning you need spaces after [[ and before ]]. There might be more bugs in your script, please debug them and if you have more specific questions, just ask and the community might be able to help.
I'm pretty much brand new to linux, and I've written a simple bash shell script that asks a user for a number and then asks for another number and displays the sum and product of the numbers. I have no problems with this, but I'm wanting to loop the script.
For instances, I want to ask the user if they want to quit, and if they choose not to quit the script starts over and asks for two numbers again. If there's anyone out there who knows stuff about loops, could you help me out please? Thanks.
Here's my code:
#!/bin/bash
echo -n "Name please? "
read name
echo "enter a number."
read number1
echo "enter another number"
read number2
echo "Thank you $name"
let i=0
let i=$number1+$number2
let x=0
let x=$number1*$number2
echo "The sum of the two numbers is: $i"
echo "The product of the two numbers is: $x"
echo "Would you like to quit? Y/N? "
quit=N
while [ "$quit" = "Y" ]
do
clear
while ["$quit" != "Y" ]
do
echo "enter a number."
read number1
echo "enter another number"
read number2
echo "Thank you $name"
let i=0
let i=$number1+$number2
let x=0
let x=$number1*$number2
echo "The sum of the two numbers is: $i"
echo "The product of the two numbers is: $x"
echo "Would you like to quit? Y/N? "
#!/bin/bash
# Initialize quit so we enter the outer loop first time
quit="N"
# Loop while quit is N
while [ "$quit" = "N" ]
do
echo -n "Name please? "
read name
echo "enter a number."
read number1
echo "enter another number"
read number2
echo "Thank you $name"
let i=0
let i=$number1+$number2
let x=0
let x=$number1*$number2
echo "The sum of the two numbers is: $i"
echo "The product of the two numbers is: $x"
#reset quit - so we enter the inner loop first time
quit=""
#we want to repeat until quit is Y or N:
#while quit is not "Y" and quit is not "N"
while [ "$quit" != "Y" -a "$quit" != "N" ]
do
echo "Would you like to quit? Y/N?"
read quit
#Convert lower case y/n to Y/N
quit=`echo $quit | tr yn YN`
done
done
while [[ "$(read -p "Quit?" q;echo $q)" != "y" ]] ; do
echo okay, go on
done
Here is a quick example of loops:
#!/bin/env bash
let quit="N"
while [ $quit != "Y" ]; do
echo "To quit, enter Y:"
read quit
done
#!/bin/bash
function sumAndProd {
read -p "enter a number: " number1
read -p "enter another number: " number2
echo "Thank you $name"
sum=$((number1+number2))
prod=$((number1*$number2))
echo "The sum of the two numbers is: $sum"
echo "The product of the two numbers is: $prod"
}
read -p "Name please? " name
quit=N
while [[ "$quit" != Y ]]
do
sumAndProd
read -p "Would you like to quit? Y/N? " quit
done
This is more a code-review.
The main thing is, to put the repeated part in a function.
instead of i, x, you better use expressive names, maybe abbreviated like sum and prod.
if you follow an assignment (let a=0) with an assignment, without using your variable before, the first assignment is senseless.
The name of the user will not change - we need to ask for this just once.
while (cond) ; do {block} done # is a form of loop.
You can specify a prompt (-p) with read, so this will end in one instead of two lines.
per se, you will not find let very often. For arithmetic expressions, x=$((expression)) is far more common.
Since you don't reuse sum and prod, you don't even need a variable. Just echo The sum is $((number1+number2))
The easiest thing to do is to loop forever and break when the user quits:
while true
do
read -p "Continue to loop? " answer
[ "n" = "$answer" ] && break
done
echo "Now I'm here!"
The break command breaks you out of the current loop and continues right after the loop. No need for a flag variable.
By the way:
[ "n" = "$answer" ] && break
Is the same as:
if [ "n" = "$answer" ]
then
break
fi
Note the -p for the prompt in the read command. That way, you can prompt and read the variable at the same time. You can also use \c in echo statements to suppress the New Line, or use printf which doesn't do a NL:
read -p "What do you want? " wants #Prompt on the same line as the read
echo "What are your desires? \c" #Prompt on the same line as the read
read desires
printf "What are your hopes? " #Prompt on the same line as the read
read hopes
Hope this helps.
#!/bin/sh
while true
do
/var/www/bash/grep_ffmpeg.sh
sleep 15
done
loop with nohup