Telefang
Telefang

Reputation: 133

Problems with the for sentence (shell script)

I don't know if I understand correctly the for sentence in shell script. This is what I'm trying to do

#!/bin/bash

echo Shows the numbers from 1 to 100 and their squares
echo

i=1

for (( i = 1; i <= 100; i++ )); do
    exp= `expr $i \* $i`
    echo "N: $i EXP: $exp"
done

And it shows: "Syntax error: Bad for loop variable"

Upvotes: 0

Views: 77

Answers (2)

user2350426
user2350426

Reputation:

If you have made the script executable: chmod u+x script.sh and you are calling it as:

$ ./script.sh

the script will load bash as the interpreter of the script.
If you are using something like: sh script.sh then it might be that your used shell is something else, like dash, ksh, zsh or some other set as the shell connected to the file link /bin/sh.

Please check Bash is the executing shell. If still in problems:

An space after the = is interpreted by the shell as a new word, which will be executed.
Therefore, trying to execute a command named 4, 9 or 16, etc. will trigger an command not found error.

This will work (no need to use i=1 as it is set at the for start):

#!/bin/bash
echo "Shows the numbers from 1 to 100 and their squares"
echo
for (( i=1; i<=100; i++ )); do
    exp=`expr $i \* $i`
    echo "N: $i EXP: $exp"
done

But really, in bash, this will be more idiomatic:

#!/bin/bash
echo -e "Shows the numbers from 1 to 100 and their squares\n"
for ((i=1; i<=100; i++)); do
    echo "N: $i EXP: $(( i**2 ))"
done

Upvotes: 2

Etan Reisner
Etan Reisner

Reputation: 80931

How are you running this script?

Are you using /bin/sh scriptfile.sh instead of /bin/bash scriptfile.sh or /path/to/scriptfile.sh?

Because that looks like a dash error because dash doesn't support the arithmetic for loop syntax.

Upvotes: 1

Related Questions