flash80
November 27, 2010, 4:14am
1
the scrip (q4.sh) should perform the following calcuation (+, -, / and *) it should be used like this:
q4.sh number1 operation number2
I wrote it already but the "*" does not work.
#!/bin/bash
#Date: 2010.10.19
# un script qui utilisera une instruction case pour effectuer des opérations arithméties :
#+ addition
#- subtraction
#x multiplication
#/ division
#Le nom du script doit etre 'q4' et il s'utilisera comme suit :
#$ ./q4 20 / 3
case $2 in "+" )
echo "`expr $1 + $3`" ;;
"-" )
echo "`expr $1 - $3`" ;;
"*" )
echo "`expr $1 * $3`" ;;
"/" )
echo "`expr $1 / $3`" ;;
esac
#END
Please give me your feedbacks how to improve it. and fix the "*". Only bash.
BR.
Have you tried calling the script like this
./q4 2 \* 2
flash80
November 27, 2010, 4:55am
3
Just tested but it returns an error
alioune@baccus ~/bashtuto/bashExercise $ ./q4.sh 2 \* 2
expr: syntax error
alioune@baccus ~/bashtuto/bashExercise $
Try:
echo "`expr $1 \* $3`" ;;
flash80
November 27, 2010, 5:43am
5
file modified
case $2 in "+" )
echo "`expr $1 + $3`" ;;
"-" )
echo "`expr $1 - $3`" ;;
"*" )
echo "`expr $1 \* $3`" ;;
"/" )
echo "`expr $1 / $3`" ;;
esac
test
alioune@baccus ~/bashtuto/bashExercise $ ./q4.sh 2 + 2
4
alioune@baccus ~/bashtuto/bashExercise $ ./q4.sh 2 - 2
0
alioune@baccus ~/bashtuto/bashExercise $ ./q4.sh 2 / 2
1
alioune@baccus ~/bashtuto/bashExercise $ ./q4.sh 2 * 2
alioune@baccus ~/bashtuto/bashExercise $
alioune@baccus ~/bashtuto/bashExercise $
Still no output for "*".
You need to call it like this:
./q4.sh 2 \* 2
---------- Post updated at 11:53 ---------- Previous update was at 11:45 ----------
You need to always escape the * on the command line to avoid expansion by the shell.
In the script, instead of using expr you can do this:
case $2 in
+) echo "$(( $1 + $3 ))" ;;
-) echo "$(( $1 - $3 ))" ;;
\*) echo "$(( $1 * $3 ))" ;;
/) echo "$(( $1 / $3 ))" ;;
esac
then you do not need the inside the arithmetic expression and you are using a shell builtin, which is faster.
In this case you could even do this:
echo "$(($@))"
but that is probably not what you are after
Do not post classroom or homework problems in the main forums. Homework and coursework questions can only be posted in this forum under special homework rules .
Please review the rules , which you agreed to when you registered, if you have not already done so.
More-than-likely, posting homework in the main forums has resulting in a forum infraction. If you did not post homework, please explain the company you work for and the nature of the problem you are working on.
If you did post homework in the main forums, please review the guidelines for posting homework and repost.
Thank You.
The UNIX and Linux Forums.