bash to prompt integers in terminal and get sum when entering = - bash

I'm looking for a rather simple solution to prompt integer numbers (one each line) into a terminal and in return for entering the equity-sign get all of them summed up.
I guess it has to look like this:
#!/bin/bash
read X
read Y
echo " $ (( X + Y ) ) "
somehow I fail to amend it properly.

Please see if below script helps. If you have any questions, please let us know.
#!/bin/bash
sum=0
number='^[0-9]+$'
equal='='
while :
do
read input
if ! [[ $input =~ $number ]] && ! [[ $input =~ $equal ]] ; then
echo -e "Please provide only numbers!"
elif [[ $input =~ $equal ]] ; then
echo -e "Sum : $sum"
break
else
let sum+=$input
fi
done
Sample Output
10
201
2202
2323
=
Sum : 4736

Related

Get user input and check it, linux

I am a beginner at unix and I am trying to use a while loop to get a user integer input for 2 numbers, but I need to check if it is an integer and reask if it's not, so I attempted to utilize if statements inside the while loop. I cannot get this to work, what am I doing wrong with the while and if loop?
#! /bin/bash
echo “Enter first number:“
while read number1
do
if[[ $number1 ]] && [ $input -eq $input 2>/dev/null ]
then
echo “$number1”
else
echo "$number1 is not an integer or not defined.Try again”
fi
done
echo “Enter second number:“
while read number2
do
if[[ $number2 ]] && [ $input -eq $input 2>/dev/null ]
then
echo “$number2”
else
echo "$number2 is not an integer or not defined.Try again”
fi
done
If you are trying to get the number and checking it until it becomes integer, Please try the below code.
#!/bin/bash
echo "enter number"
while read number1
do
if ! [[ $number1 =~ ^[0-9]+$ ]]
then
echo "number is not an integer"
else
echo "number is an integer"
exit;
fi
done

Shell Script - Case statement which finds exactly numbers (without +,-,/,*)

Briefly,
I have a variable ($num) which contains random number(max.18), I need a case statement in shell (because along with checking number, I also have some alphabet conditions) which should validate the user input with the variable (must be less than $num).
Ex:
case $input in
...
1) ... ;;
2) ... ;;
...
so, here if I have only two conditions than I can write code like this, but my variable $num contains random number, how can I write case conditions which satisfies my below requirements.
If user inputs numbers like (1/3,3*1,3-2,2+1) it should not validate as a number
If user inputs numbers like (0001 or 01 or 000001) it should not validate as a number
The case condition should execute only if user inputs number between 1-$num no other number formats or symbols should not allowed.
Ex:
case $input in
[nN*]) ...
[aA*]) ...
...
*) if echo "$input" | egrep '^\-?[0-9]+$'; then
typeset -LZ num
num="$input"
if [ "$input" != "$num" ]; then
echo "$input not a valid number"
fi
else
echo "please choose proper choice option"
fi
;;
This code works but I want a normal case condition which should satisfy my requirements like if we have two or three options we can simply write the code but what if we have random options (which may decrease or increase) how to write a case condition in that case.
Thanks!
If the usage of a case is not compulsory, try and use some regex validation to have more control on what is allowed and what not:
[[ $input =~ ^[1-9][0-9]*$ ]]
# ^ ^ ^ ^
# beginning | | end
# | any digit
# a digit from 1 to 9
This checks that the data in $input contains a number that does not start with 0.
$ r=001
$ [[ $r =~ ^[1-9][0-9]*$ ]] && echo "yes"
$
$ r=1
$ [[ $r =~ ^[1-9][0-9]*$ ]] && echo "yes"
yes
$ r="3+1"
$ [[ $r =~ ^[1-9][0-9]*$ ]] && echo "yes"
$
You can then check if the number is lower than the stored one:
[ $r -le $num ]
All together:
$ num=15
$ r=5
$ [[ $r =~ ^[1-9][0-9]*$ ]] && [ $r -le $num ] && echo "yes"
yes
$ r=19
$ [[ $r =~ ^[1-9][0-9]*$ ]] && [ $r -le $num ] && echo "yes"
$
$ r="3+1"
$ [[ $r =~ ^[1-9][0-9]*$ ]] && [ $r -le $num ] && echo "yes"
$
read -p "enter number" yournumber
re='^[0-9]+$'
if ! [[ $yournumber =~ $re ]] ; then
echo "error: Not a number" >&2; exit 1
fi
This is only code rest of the things you need to do it.

Simple Shell/Bash Program Syntax

I have the following bash script:
#!/bin/bash
if [ ! -f numbers ]; then echo 0 > numbers; fi
count = 0
while [[$count != 100]]; do
count = `expr $count + 1`
done
When I run it in terminal on my Mac, I get the following output:
seq_file_gen.sh: line 3: count: command not found
seq_file_gen.sh: line 4: [[: command not found
Why am I getting these errors? This script was given to me by my teacher so I have no idea why I can't get this script to run. Any help would be greatly appreciated.
EDIT:
This is the correct way to write this script (with spaces)
#!/bin/bash
if [ ! -f numbers ]; then echo 0 > numbers; fi
count=0
while [[ $count != 100 ]]; do
count=`expr $count + 1`
done
Add spaces before/after [[ and ]] like so:
while [[ $count != 100 ]]; do

Checking if char is within set

I'm trying to check if some string from length 1 and has only following chars: [RGWBO].
I'm trying the following but it doesn't work, what am I missing?
if [[ !(${line[4]} =~ [RGWBO]) ]];
This is what you want:
if [[ ${line[4]} =~ ^[RGWBO]+$ ]];
This means that the string right from the start till the end must have [RGWBO] characters one or more times.
If you want to negate the expression just use ! in front of [[ ]]:
if ! [[ ${line[4]} =~ ^[RGWBO]+$ ]];
Or
if [[ ! ${line[4]} =~ ^[RGWBO]+$ ]];
This one would work with any usable version of Bash:
[[ -n ${LINE[0]} && ${LINE[0]} != *[^RGWB0]* ]]
Even though I prefer the simplicity of extended globs:
shopt -s extglob
[[ ${LINE[0]} == +([RGWBO]) ]]
Use expr (expression evaluator) to do substring matching.
#!/bin/bash
pattern='[R|G|W|B|O]'
string=line[4]
res=`expr match "$string" $pattern`
if [ "${res}" -eq "1" ]; then
echo 'match'
else
echo 'doesnt match'
fi
Approach
Test the string length with ${#myString}, if it's egal to 1 proceed to step 2 ;
Does is contains your pattern.
Code
re='[RGWBO]';
while read -r line; do
if (( ${#line} == 1 )) && [[ $line == $re ]]; then
echo "yes: $line"
else
echo "no: $line"
fi
done < test.txt
Resources
You may want to look at the following links:
Bash: Split string into character array's answer ;
Length of a string, use ${#myString} ;
Extracting parts of strings, use ${myString:0:8} ;
Data
The test.txt file contains this
RGWBO
RGWB
RGW
RG
R
G
W
B
O
V

Check if a number is even in shell

I need to check if a number is even.
Here's what I've tried.
newY="281"
eCheck=$(( $newY % 2 ))
echo $newY
echo $eCheck
while [ $eCheck -eq 0 ]; do
newY=$((newY-1))
eCheck=$(( $newY % 2 ))
echo $newY
done
...
returns eCheck = 1
how can it be? 281/2 = 140.5
i've also tried using bc, but it went into an infinite loop eCheck=$(echo "scale=1;$newY%2" | bc)
Nici is right, "%" is the modulo, and gives you the remainder of the division.
Your script can be simplified as follows :
if [[ $((var % 2)) -eq 0 ]];
then echo "$var is even";
else echo "$var is odd";
fi
You can do a simple :
eCheck=$(( $newY & 1 ))
to utilize the bitwise operators in bash.
The % operator computes the remainder. So 281 % 2 is 1, because 281 divided by 2 is 140 with a remainder of 1.
#!/usr/bin/env bash
[[ $( expr $1 % 2 ) -eq 0 ]] && echo "Even Number" || echo "Odd Number"
You are so close! Think of it like this. There are only two possible answers for Y in the expression
Y = X % 2
for ALL values of X. What are they? Play with a few values of X to see if you can come up with the values for Y.
Next, is there anything you can determine about what the value of Y says about the value of X? That is, can you use the value of Y to answer the problem you are trying to solve?
This can be done using expr
evenCheck=$(expr $newY % 2)
if [ $evenCheck = 0 ] ;
then echo "number is even";
else echo "number is odd";
fi
done
As you mention you are checking even for single no, So there is no need to use a loop. Here is my bit of code.
read -p "Enter a number: " num
if [ $((num%2)) -eq 0 ]
then
echo "Entered Number is even:"
else
echo "Entered Number is odd:"
fi
Since this question is tagged as Bash, the right way to check if a number is even in Bash is:
if ((num%2 == 0)); then
echo "The number is even"
fi
or, more even shorter:
if ((num % 2)); then
echo "The number is even"
fi
We don't need to use [[ ... ]] in this case.
See also:
Difference between Bash operators double vs single brackets and (( (on Unix & Linux Stack Exchange)
How do I check whether a variable has an even numeric value?
#!bin/bash
echo "Type the input integer, followed by [Enter]:"
read x
if [ $((x%2)) -eq 0 ]; then
echo "$x is even"
else
echo "$x is odd"
fi
Yes "%" is modulo, it gives you the remainder like others have mentioned

Resources