dawnoflife
dawnoflife

Reputation: 1652

Looping through files bash script

I am trying to run a simple loop through all files script but it's giving me the following error. The script is called test.sh and I am using Cygwin on Windows 7.

My script:

#!/bin/bash
FILES = "/bowtie-0.12.7-win32/bowtie-0.12.7/output_635_25bp/*"
for f in $FILES
do
    echo "hello world"
done

The error is:

./test.sh: line 2: FILES: command not found
./test.sh: line 4: syntax error near unexpected token ``$'do\r''
./test.sh: line 4: ``do

Before running the script I converted all the files in folder to unix format using dos2unix command.

Upvotes: 4

Views: 9634

Answers (5)

Mike
Mike

Reputation: 1

I have same the error:

./test.sh: line 2: FILES: command not found ./test.sh: line 4: syntax error near unexpected token $'do\r'' ./test.sh: line 4: do

I fixed it by change the ends line from 'CR LF' to 'LF' on the Cygwin when I run it on the windows

Upvotes: 0

chris2k
chris2k

Reputation: 169

Try to use the find-command

for i in `find /bow.../ -type f`
do
  echo "hello world"
done

because ls will return directories too.

http://infofreund.de/bash-loop-through-files/

Upvotes: 0

me_and
me_and

Reputation: 15664

Collating other folks' answers into a single one.

You've two problems with this script:

  • The script still has Windows line endings (that's what the \r refers to; it's the character that Windows has in its line endings, but Unix doesn't). bcarlso pointed that one out. Run dos2unix over the script to sort it out.

  • When assigning variables in a bash script, you cannot have spaces around the = sign. scibuff caught that one.

    The below gets interpreted as trying to run the command FILES (which doesn't exist) with the arguments = "/bowtie...".

    FILES = "/bowtie-0.12.7-win32/bowtie-0.12.7/output_635_25bp/*"
    

    Whereas the below is interpreted as assigning "/bowtie..." to the variable FILES:

    FILES="/bowtie-0.12.7-win32/bowtie-0.12.7/output_635_25bp/*"
    

Upvotes: 2

bcarlso
bcarlso

Reputation: 2345

Try:

for f in `ls /bowtie-0.12.7-win32/bowtie-0.12.7/output_635_25bp/*`; do echo "hello world"; done

Thanks!

Brandon

Upvotes: 4

scibuff
scibuff

Reputation: 13755

try

FILES=/bow.../*
for f in $FILES
do
   echo "hello world"
done

i.e. no spaces around ' = '

Upvotes: 1

Related Questions