Bash Scripting Multiplication table - bash

Hello I am wondering if anyone can help me :
I try to make a multiplication table for my daughter, I don't know how to make it. This is how I want to look :
1 x 1 = ? answer
if the answer is true then go to the next one
1 x 2 = ?
but if the answer is false then ask again 1 x 1 = ?
until the answer is Correct.
#!/bin/bash
# Multiplication table
echo " --== Multiplication Table ==-- "
sleep 2
echo " Lesson 1"
sleep 1
echo ""
echo -n "1 x 1 = ? " ; read opt
if [ "$opt" = 1 ]
then
echo "Correct!"
else
echo "Wrong!"
fi
sleep 1
echo ""
echo -n "1 x 2 = ? " ; read opt
if [ "$opt" = 2 ]
then
echo "Correct!"
else
echo "Wrong!"
fi
After the exercise is done until 10. Then show a result of how many correct answers has and how many Wrong.
Example:
Lesson 1 is finish you have 9 correct answers and 1 wrong answer !

You can use this script:
#!/bin/bash
# Multiplication table
echo " --== Multiplication Table ==-- "
sleep 2
echo " Lesson $1"
sleep 1
echo ""
wrong=0
correct=0
for i in {1..10}
do
while true
do
echo -n "$1 x $i = ? " ; read opt
if [ $opt = $(( $1 * $i )) ]
then
(( correct++ ))
echo "Correct!"
break
else
(( wrong++ ))
echo "Wrong!"
fi
done
done
echo "Lesson $1 is finish you have $correct correct answers and $wrong wrong answer!"
You can run it with different params for any base. Such as ./script 5 for multiplication with 5.

I made it. This is how I want to look like and work
#!/bin/bash
# Multiplication table
echo " --== Multiplication Table ==-- "
sleep 2
echo " Lesson 1"
sleep 1
echo ""
while true
do
echo -n "1 x 1 = ? " ; read opt
if [ $opt = 1 ]
then
(( correct++ ))
echo "Correct!"
break
else
(( wrong++ ))
echo "Wrong!"
fi
done
while true
do
echo -n "1 x 2 = ? " ; read opt
if [ $opt = 2 ]
then
(( correct++ ))
echo "Correct!"
break
else
(( wrong++ ))
echo "Wrong!"
fi
done
while true
do
echo -n "1 x 3 = ? " ; read opt
if [ $opt = 3 ]
then
(( correct++ ))
echo "Correct!"
break
else
(( wrong++ ))
echo "Wrong!"
fi
done
while true
do
echo -n "1 x 4 = ? " ; read opt
if [ $opt = 4 ]
then
(( correct++ ))
echo "Correct!"
break
else
(( wrong++ ))
echo "Wrong!"
fi
done
while true
do
echo -n "1 x 5 = ? " ; read opt
if [ $opt = 5 ]
then
(( correct++ ))
echo "Correct!"
break
else
(( wrong++ ))
echo "Wrong!"
fi
done
while true
do
echo -n "1 x 6 = ? " ; read opt
if [ $opt = 6 ]
then
(( correct++ ))
echo "Correct!"
break
else
(( wrong++ ))
echo "Wrong!"
fi
done
while true
do
echo -n "1 x 7 = ? " ; read opt
if [ $opt = 7 ]
then
(( correct++ ))
echo "Correct!"
break
else
(( wrong++ ))
echo "Wrong!"
fi
done
while true
do
echo -n "1 x 8 = ? " ; read opt
if [ $opt = 8 ]
then
(( correct++ ))
echo "Correct!"
break
else
(( wrong++ ))
echo "Wrong!"
fi
done
while true
do
echo -n "1 x 9 = ? " ; read opt
if [ $opt = 9 ]
then
(( correct++ ))
echo "Correct!"
break
else
(( wrong++ ))
echo "Wrong!"
fi
done
while true
do
echo -n "1 x 10 = ? " ; read opt
if [ $opt = 10 ]
then
(( correct++ ))
echo "Correct!"
break
else
(( wrong++ ))
echo "Wrong!"
fi
done
echo "Lesson 1 is finish you have $correct correct answers and $wrong wrong answer!"

#!/bin/bash
#######multiplication table#########
INPUT_NUMBER=$1
if [[ $# -ne 1 ]]; then
echo "please enter at least 1 number"
exit 1
fi
if [[ ! ${INPUT_NUMBER} =~ [[:digit:]] ]];then
echo "Incorrect usage, wrong type args"
echo "Usage is $0 <number>"
exit 1
fi
for i in {1..10}
do
echo "${INPUT_NUMBER} * ${i} = $((${INPUT_NUMBER} * ${i}))"
done

Related

How to call variable outside function?

Im trying to call a variable I have set to get the total time elasped for said function but for some reason it won't let me use it outside or it gives me the wrong output. Any ideas on what is wrong
recur_fib()
{
first_num=$1
start=$SECONDS
[ $first_num -lt 2 ] && echo -n $first_num || echo -n $(( $( recur_fib $(( first_num - 1 )) ) + $( recur_fib $(( first_num - 2 )) ) ))
elapsedtime=$(($SECONDS - $start))
}
total_time_recur=$(recur_fib $elapsedtime)
val=$(recur_fib $1)
Where I'm trying to call it
case $method in
"N" | "n")
echo "You chose non-recursive";;
"R" | "r")
#repeat the the method and number chosen
echo -e "RECURSIVE $1\n"
echo -e "Run\tFibonacci\tTime"
count=1
while [ $count -le $1 ]
do
echo -e "$count" '\t' $val '\t' $total_time_recur
((count = count + 1))
done
;;
*)
echo "Please chose either R,r or N,n"
esac

Write a function in shell script to check if the two numbers are Palindromes

I'm writing a function in shell script to check if the two numbers are Palindromes but I am getting an error, It is showing error in line 18 command not found. Please help me how can I remove this error.
#!/bin/bash
echo "Enter two number:"
read a
read b
for num in $a $b;
do
x=$x$sep$num
sep=" "
done
y=$x
num1=$a
num2=$b
rem=""
rev=0
for word in $y;
do
checkPalindrome $word
if [ $? -eq 0 ]
then
echo "$word is palindrome"
fi
done
checkPalindrome() {
local s=$1
for i in $s ;
do
while [ $i -gt 0]
do
rem=$(($i%10));
rev=$(($rev*10+$rem));
i=$(($i / 10));
done
done
if [[ $rev -eq $num1 && $rev -eq $num2 ]]
then
return 0;
else
return 1;
fi
}
You need to provide your checkPalindrome() definition before you use it, as below:
#!/bin/bash
checkPalindrome() {
local s=$1
for i in $s
do
while [ "$i" -gt 0 ]
do
rem=$((i%10))
rev=$((rev*10+rem))
i=$((i / 10))
done
done
if [[ $rev -eq $num1 && $rev -eq $num2 ]]
then
return 0
else
return 1
fi
}
echo "Enter two number:"
read -r a
read -r b
for num in $a $b
do
x="$x$sep$num"
sep=" "
done
y="$x"
num1="$a"
num2="$b"
rem=""
rev=0
for word in $y;
do
if checkPalindrome "$word"
then
echo "$word is palindrome"
fi
done
You could consider the input as string (you don't have to restrict it to be an integer)
#!/bin/bash
is_palindrome() {
local arg=$1 i j
for ((i = 0, j = ${#arg} - 1; i < j; ++i, --j)); do
[[ ${arg:i:1} = "${arg:j:1}" ]] || return
done
}
read -r -p 'Enter two words: ' a b
for word in $a $b; do
is_palindrome "$word" && echo "$word is palindrome"
done

Values of an array not comparing to numbers correctly

Im trying to get an array from grades.txt, and determine what letter grade it should be assigned.
I either get
hw4part2.sh: line 26: [: : integer expression expected
If i use -ge or
hw4part2.sh: line 26: [: : unary operator expected
If i use >=
Below is the code im trying to get working
mapfile -t scores < grades.txt
numOScores=0
numOA=0
numOB=0
numOC=0
numOD=0
numOF=0
DoneWScores=0
A=90
B=80
C=70
D=60
F=59
while [ $DoneWScores -eq 0 ]
do
numOScores=$((numOScores + 1))
if [ "${scores[$numOScores]}" -ge "$A" ]
then
echo "A"
elif [ "${scores[$numOScores]}" -ge "$B" ]
then
echo "B"
elif [ "${scores[$numOScores]}" -ge "$C" ]
then
echo "C"
elif [ "${scores[$numOScores]}" -ge "$D" ]
then
echo "D"
elif [ "${scores[$numOScores]}" -le "$F" ]
then
echo "F"
else
echo "Done/error"
DoneWScores=1
fi
done
If anyone knows what my problem is, that'd be greatly appreciated
Consider this:
#!/usr/bin/env bash
if (( ${BASH_VERSINFO[0]} < 4 )); then
echo "Bash version 4+ is required. This is $BASH_VERSION" >&2
exit 1
fi
letterGrade() {
if (( $1 >= 90 )); then echo A
elif (( $1 >= 80 )); then echo B
elif (( $1 >= 70 )); then echo C
elif (( $1 >= 60 )); then echo D
else echo F
fi
}
declare -A num
while read -r score; do
if [[ $score == +([[:digit:]]) ]]; then
grade=$(letterGrade "$score")
(( num[$grade]++ ))
echo "$grade"
else
printf "invalid score: %q\n" "$score"
fi
done < grades.txt
for grade in "${!num[#]}"; do
echo "$grade: ${num[$grade]}"
done | sort

How can I prevent and optimize a bad variable name?

When I run the code the output is ./fib.sh: 43: read: 6: bad variable name. What does it mean and how do I fix it?
case $# in
0)
echo "plz insert 3 integer number \n" && read a b n;;
1)a=$1 && echo "plz insert 2 integer number\n " && read b n ;;
2) a=$1 b=$2 && echo "plz insert 1 intger number \n" && read n ;;
3)a=$1 b=$2 n=$3 ;;
*)echo "The number of arguments is more than 3\n" && exit 1 ;;
esac
echo " a=$a b=$b n=$n\n"
while true ; do
if [ $n -eq 0 ] ;then
echo $a
elif [ $n -eq 1 ];then
echo $b
elif [ $n -ge 2 ] ; then
printf "%s ""$a"
printf "%s ""$b"
count=1
c=`expr $n - 1`
while [ $count -le $c ] ; do
printf "%s ""$answer"
answer=`expr $a + $b`
a=$b
b=$answer
count=`expr $count + 1`
done
echo "\nDo you want to try another n (yes/no):\n"
read s
case $s in
yes) echo"\nenter new value of n \n" && read $n && continue ;;
no) echo "Thank you" && exit 1 ;;
esac
fi
done
read: 6: bad variable name.
read $n expands the value of the variable n which, in this case, is 6. So that's read 6 trying to read into the variable 6. 6 is not a valid variable name in shell.
From context, you want to read into n which is read n.
yes) echo"\nenter new value of n \n" && read n && continue ;;

Creating a calculator script

I am trying to make a calculator with a bash script.
The user enters a number, chooses whether they wish to add, subtract, multiply or divide. Then the user enters a second number and is able to choose whether to do the sum, or add, subtract, multiply or divide again on a loop.
I cannot rack my head around this right now
echo Please enter a number
read number
echo What operation would you like to perform: 1: Add, 2: Subtract, 3: Multiple, 4: Divide
read operation
case $operation in
1) math='+';;
2) math='-';;
3) math='*';;
4) math='/';;
*) math='not an option, please select again';;
esac
echo "$number $math"
echo Please enter a number
read number2
echo What operation would you like to perform: 1: Add, 2: Subtract, 3: Multiple, 4: Divide, 5: Equals
read operation2
case $operation2 in
1)math2='Add';;
2)math2='Subtract';;
3)math2='Multiply';;
4)math2='Divide';;
5)math2='Equals';;
*)math2='not an option, please select again';;
esac
echo You have selected $math2
exit 0
This is what I have done so far, but can anyone help me work out how to loop back on the calculator?
The lesser-known shell builtin command select is handy for this kind of menu-driven program:
#!/bin/bash
while true; do
read -p "what's the first number? " n1
read -p "what's the second number? " n2
PS3="what's the operation? "
select ans in add subtract multiply divide; do
case $ans in
add) op='+' ; break ;;
subtract) op='-' ; break ;;
multiply) op='*' ; break ;;
divide) op='/' ; break ;;
*) echo "invalid response" ;;
esac
done
ans=$(echo "$n1 $op $n2" | bc -l)
printf "%s %s %s = %s\n\n" "$n1" "$op" "$n2" "$ans"
done
Sample output
what's the first number? 5
what's the second number? 4
1) add
2) subtract
3) multiply
4) divide
what's the operation? /
invalid response
what's the operation? 4
5 / 4 = 1.25000000000000000000
If I was going to get fancy with bash v4 features and DRY:
#!/bin/bash
PS3="what's the operation? "
declare -A op=([add]='+' [subtract]='-' [multiply]='*' [divide]='/')
while true; do
read -p "what's the first number? " n1
read -p "what's the second number? " n2
select ans in "${!op[#]}"; do
for key in "${!op[#]}"; do
[[ $REPLY == $key ]] && ans=$REPLY
[[ $ans == $key ]] && break 2
done
echo "invalid response"
done
formula="$n1 ${op[$ans]} $n2"
printf "%s = %s\n\n" "$formula" "$(bc -l <<< "$formula")"
done
Wrapping Code in a Loop
If you just want to wrap your code in a Bash looping construct, and are willing to hit CTRL-C to terminate the loop rather than do something more fancy, then you can wrap your code in a while-loop. For example:
while true; do
: # Your code goes here, inside the loop.
done
Just make sure to move your unconditional exit statement out of the body of the loop. Otherwise, the loop will terminate whenever it reaches that line.
For your ~/.bashrc:
alias bc="BC_ENV_ARGS=<(echo "scale=2") \bc"
Just use bc, with that alias it automatically works with two decimals instead of integers.
!/bin/bash
PS3="what's the operation? "
declare -A op=([add]='+' [subtract]='-' [multiply]='*' [divide]='/')
while true; do
read -p "what's the first number? " n1
read -p "what's the second number? " n2
select ans in "${!op[#]}"; do
for key in "${!op[#]}"; do
[[ $REPLY == $key ]] && ans=$REPLY
[[ $ans == $key ]] && break 2
done
echo "invalid response"
done
formula="$n1 ${op[$ans]} $n2"
printf "%s = %s\n\n" "$formula" "$(bc -l <<< "$formula")"
done
Please use the following script.
clear
sum=0
i="y"
echo " Enter one no."
read n1
echo "Enter second no."
read n2
while [ $i = "y" ]
do
echo "1.Addition"
echo "2.Subtraction"
echo "3.Multiplication"
echo "4.Division"
echo "Enter your choice"
read ch
case $ch in
1)sum=`expr $n1 + $n2`
echo "Sum ="$sum;;
2)sum=`expr $n1 - $n2`
echo "Sub = "$sum;;
3)sum=`expr $n1 \* $n2`
echo "Mul = "$sum;;
4)sum=`expr $n1 / $n2`
echo "Div = "$sum;;
*)echo "Invalid choice";;
esac
echo "Do u want to continue ?"
read i
if [ $i != "y" ]
then
exit
fi
done
#calculator
while (true) # while loop 1
do
echo "enter first no"
read fno
if [ $fno -eq $fno 2>/dev/null ]; # if cond 1 -> checking integer or not
then
c=1
else
echo "please enter an integer"
c=0
fi # end of if 1
if [ $c -eq 1 ]; #if 2
then
break
fi # end of if 2
done # end of whie 1
while(true) #while loop 2
do
echo "enter second no"
read sno
if [ $sno -eq $sno >/dev/null 2>&1 ] # if cond 3 -> checking integer or not
then
c=1
else
echo "please enter an integer"
c=0
fi # end of if 3
if [ $c -eq 1 ] # if cond 4
then
break
fi # end of if 4
done #2
while(true) # while loop 3
do
printf "enter the operation (add,div,mul,sub) of $fno and $sno\n"
read op
count=0
##addition
if [ $op = add ] #if cond 5
then
echo "$fno+$sno is `expr $fno + $sno`"
#multiplication
elif [ $op = mul ];
then
echo "$fno*$sno is `expr $fno \* $sno`"
#substraction
elif [ $op = sub ]
then
while(true) #while loop 3.1
do
printf "what do you want to do??? \n 1. $fno-$sno \n 2. $sno-$fno"
printf "\n press the option you want to perform?(1 or 2)\n"
read opt
if [ $opt = 1 ] #if cond 5.1
then
echo "$fno-$sno is `expr $fno - $sno`"
break
elif [ $opt = 2 ]
then
echo " $sno-$fno is `expr $sno - $fno`"
break
else "please enter valid options to proceed(1 or 2)";
clear
fi #end of if 5.1
done # end of 3.1
#division
elif [ $op = div ]
then
while(true) # whilw loop 3.2
do
printf "what do you want to do??? \n 1. $fno/$sno \n 2. $sno/$fno"
printf "\n press the option you want to perform?(1 or 2)\n"
read opt
if [ $opt = 1 ] #if cond 5.2
then
echo "$fno divided by $sno is `expr $fno / $sno`"
break
elif [ $opt = 2 ]
then
echo " $sno divided by $fno is `expr $sno / $fno`"
break
else
clear
fi #end of if 5.2
done # end of 3.2
else
echo "valid option please!!!"
count=1
fi # end of if 5
if [ $count -eq 0 ] #if cond 6
then
echo "Do you want to do more ops"
echo "(y/n)"
read ans
clear
if [ $ans = n ] # if 6.1
then
break
fi # end of if 6.1
fi #end of if 6
done #end of while 3

Resources