遍历文件的bash脚本

4
我可以帮助您进行文本翻译。以下为需要翻译的内容:

我试图运行一个简单的循环脚本,遍历所有文件,但是出现了以下错误。脚本名为test.sh,我正在使用Windows 7上的Cygwin。

我的脚本:

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

错误是:

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

在运行脚本之前,我使用 dos2unix 命令将文件夹中的所有文件转换为 Unix 格式。
5个回答

4

尝试:

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

感谢! Brandon

嗯...我正在运行OSX,所以我无法在Cygwin中尝试它,但是将该代码粘贴到我的shell并更改目录后,它对我有效。您是否也将test.sh文件转换为dos2unix格式? - bcarlso

2

将其他人的答案整合成一个。

这个脚本有两个问题:

  • 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/*"
    

另外,我还会添加有关解析ls输出的常规警告 - suvayu

1
尝试一下
FILES=/bow.../*
for f in $FILES
do
   echo "hello world"
done

即不要在“=”周围加上空格。


它仍然给我syntax error near unexpected token $ do\r - dawnoflife

0

我遇到了同样的错误:

./test.sh: 第2行: FILES: 找不到命令 ./test.sh: 第4行: 附近有语法错误的令牌$'do\r'' ./test.sh: 第4行: do

我通过将行尾从“CR LF”更改为在Windows上运行时的“LF”来解决它,因为我在Cygwin上运行。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接