Unix & Linux: Adding two numbers using expr (3 Solutions!!)
Unix & Linux: Adding two numbers using expr
The Question: I'm learning Shell scripting for a diploma in IT I'm currently doing. I'm
trying to write a small script that adds two numbers as shown as in one of the
tutorials we were given.
echo "Enter two numbers"
read num1 num2
sum = 'expr $num1 + $num2'
echo "The sum is = $sum"
However when I give it the execution permission and run the script, it gives me
this error.
sum: =. No such file or directory.
sum: expr $num1 + $num2: No such file or directory
I tried running this on both Ubuntu and Fedora but same error occurs. Can
anyone please tell me what I'm missing here?
Solutions: Please watch the whole video to see all solutions, in order of how many people found them helpful
== This solution helped 41 people ==
First you have to get rid of the spaces for the assignment, e.g
sum='expr $num1 + $num2'
then you have to change ' to a ` or even better to $():
sum=$(expr "$num1" + "$num2")
instead of using expr you can also do the calculation directly in your shell:
sum=$((num1 + num2))
== This solution helped 9 people ==
You have probably misread backticks as single quotes in the line:
sum = 'expr $num1 + $num2'
See http://mywiki.wooledge.org/BashFAQ/082 on using $(...) instead.
This works as expected:
sum=$(expr "$num1" + "$num2")
Also note there are no gaps around the equals sign (the variable assignment).
With thanks & praise to God, and with thanks to the many people who have made this project possible! | Content (except music & images) licensed under cc by-sa 3.0 | Music: https://www.bensound.com/royalty-free-music | Images: https://stocksnap.io/license & others | With thanks to user Ulrich Dangel (https://unix.stackexchange.com/users/8979), user Stephane Chazelas (https://unix.stackexchange.com/users/22565), user Premraj (https://unix.stackexchange.com/users/102396), user jasonwryan (https://unix.stackexchange.com/users/6761), user Isuru (https://unix.stackexchange.com/users/21761), and the Stack Exchange Network (http://unix.stackexchange.com/questions/44995). Trademarks are property of their respective owners. Disclaimer: All information is provided "AS IS" without warranty of any kind. You are responsible for your own actions. Please contact me if anything is amiss at Roel D.OT VandePaar A.T gmail.com.
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Unix & Linux: Adding two numbers using expr (3 Solutions!!)», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.