Linux Script - Help

MatiasZ

Regular
I need to write a VERY SIMPLE linux script for my class, but I'm doing something wrong (which is a matter of sintax I think) and have not been able to find it easily on google.

The program must put out on the screen the numbers from 0 till the value passed by the cmd line. For example, if you run ./script.sh 5 the program will output '1 2 3 4 5'. So I've used a while sentence, and my script looks like this:

Code:
 #!/bin/sh
num=0
while [ $num -ne $1 ]; do
  num = $num + 1     <-------------------- THIS IS THE LINE WITH PROBLEMS
  echo $num
done

The problem is in the line marked above, and I'm not sure how I should be doing this. Any help will be greatly appreciated (especially since I have to send it in tonight as latest) ;)
 
DiGuru said:
just do this:

#!/bin/sh

num = 0
while [num -ne $1]
do
num = num + 1
echo num
done

If I write it like that, whenever I run the script I get:

'./loop.sh: line 6: num: command not found'

Which is the same I was getting before :( However, after reading the links you gave me, I found I needed to write it like this:

Code:
#!/bin/sh
num = 0
while [num -ne $1]
do
    num = 'expr $num + 1'
    echo num
done

That way works perfectly :) Thank you for all the help!
 
MatiasZ said:
If I write it like that, whenever I run the script I get:

'./loop.sh: line 6: num: command not found'

Which is the same I was getting before :( However, after reading the links you gave me, I found I needed to write it like this:

Code:
#!/bin/sh
num = 0
while [num -ne $1]
do
    num = 'expr $num + 1'
    echo num
done

That way works perfectly :) Thank you for all the help!


And if you happen to run bash (likely bourne shell compatible choice on linux):

num = $(( $num + 1 ))

"man bash" is your friend (or foe ;) , you'll get to love that manpage after a few years reading it)
 
I have a book called "Linux - Shells By Example", which was written by Ellie Quigley. It's the text I used at school, and it's very good. The man pages should have all the information you need, but this book has a lot of really good in-depth examples. I found it quite handy.
 
I actually AM running 'bash' on my SuSe and Slack systems, but the shell on the college lab's is 'sh', that's why I'm using it 'hardcoded' on the script so to make sure it runs good there.

Thank you all for the answers, you've been really helpfull ;)
 
Back
Top