LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   my first script (https://www.linuxquestions.org/questions/linux-newbie-8/my-first-script-935470/)

rit 03-20-2012 09:05 AM

my first script
 
hello everyone,
this is the script i have written from the ebook i m referring to
#!/bin/sh
echo "enter x"
read x
echo "enter y"
read y
echo "$[x*y]"
the problem is the value of x and y is not
being evaluated in last echo command

yancek 03-20-2012 09:21 AM

Change the last echo line. You didn't put spaces before the x and after the y:
Quote:

echo "$[ x*y ]"

David the H. 03-20-2012 09:30 AM

Congratulations on beginning your scripting journey.

First of all, please use [code][/code] tags around your code and data, to preserve formatting and to improve readability. Please do not use quote tags, colors, or other fancy formatting.

Second, clean, consistent formatting makes code readable and more easily debuggable. Indent all your sub-commands, and separate logical sections with whitespace. Add comments anywhere the code isn't completely obvious (and remember, what seems obvious to you now will not be a year or so down the line).

Third, $[..] is deprecated syntax. arithmetic expressions should be done these days with $((..)) or ((..)).

Other than that, there are no syntax errors in your code, and it runs for me as posted. You should however use #!/bin/bash instead of #!/bin/sh (assuming you are coding for bash, of course). Using "sh" means that the script will be interpreted as a posix-compliant script, and many shell-specific features will be unavailable or have altered behavior.

Also, your next step should be to do some input checking on the variables, to make sure you're actually getting integers before you process them. This usually means running the input part in a loop, with an if or case statement for testing the value.

Code:

while true; do

        echo "enter x"
        read x

        case $x in
                *[^0-9]*) echo "Not an integer, try again."
                          continue
                ;;
        esac

        break
done


rit 03-20-2012 09:31 AM

thank you for reply
i did as you said but still it's displaying $[ x*y ]
after reading the value in x and y

David the H. 03-20-2012 09:45 AM

As I said, that syntax is deprecated, and not supported by all shells.

I can now reproduce your behavior by using dash as my shell instead, which many distros use for processing "sh" scripts. So your system is likely using dash to interpret posix scripts, and dash doesn't support "$[..]".

So change your script to "$(( x * y ))", and change your shebang to #!/bin/bash, as I suggested before.

rit 03-20-2012 11:06 AM

i changed it from #!/bin/sh to #!/bin/bash and it worked.
late reply due to net problem.
thank you


All times are GMT -5. The time now is 11:38 AM.