-1

This is a very weird problem. I run test.sh using sh test.sh but it returns an error as mentioned in the subject line.

Here's the code for reference:

#!/bin/bash

foreach n ( 1 2 3 4 5 )
  echo $n
end

It's just a simple loop but it won't execute. Complete error below:

test.sh: 3: test.sh: Syntax error: "(" unexpected
Rav
  • 1,327
  • 3
  • 18
  • 32
  • 5
    it doesn't work because it isn't a valid bash syntax – Inian Sep 05 '19 at 07:14
  • 1
    See how to iterate over a range in `bash` here - [How do I iterate over a range of numbers defined by variables in Bash?](https://stackoverflow.com/q/169511/5291015) – Inian Sep 05 '19 at 07:16

3 Answers3

4

There's no foreach in bash. What you've tried works in tcsh or csh.

The corresponding bash syntax is

for n in 1 2 3 4 5 ; do
    echo $n
done
choroba
  • 231,213
  • 25
  • 204
  • 289
2

foreach is not available in bash. It is for instead.

For simple range based iterations,

for n in {1..5};
do
  echo $n;
done

works in reverse too: {5..1} Alphabets: {a..z} {z..a}

For more range based iterations with step != 1, use seq

chepner
  • 497,756
  • 71
  • 530
  • 681
Sam Daniel
  • 1,800
  • 12
  • 22
1

Change it to this:

#!/bin/bash

for n in  1 2 3 4 5
do
  echo $n
done
Spydernaz
  • 847
  • 2
  • 8
  • 14