循环遍历文件 bash 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9677203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Looping through files bash script
提问by dawnoflife
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.shand I am using Cygwin on Windows 7.
我试图通过所有文件脚本运行一个简单的循环,但它给了我以下错误。脚本被调用test.sh,我在 Windows 7 上使用 Cygwin。
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 dos2unixcommand.
在运行脚本之前,我使用dos2unix命令将文件夹中的所有文件转换为 unix 格式。
采纳答案by bcarlso
Try:
尝试:
for f in `ls /bowtie-0.12.7-win32/bowtie-0.12.7/output_635_25bp/*`; do echo "hello world"; done
Thanks!
谢谢!
Brandon
布兰登
回答by me_and
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
\rrefers to; it's the character that Windows has in its line endings, but Unix doesn't). bcarlsopointed that one out. Rundos2unixover the script to sort it out.When assigning variables in a bash script, you cannot have spaces around the
=sign. scibuffcaught 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 variableFILES:FILES="/bowtie-0.12.7-win32/bowtie-0.12.7/output_635_25bp/*"
该脚本仍然具有 Windows 行尾(这就是
\r所指的;这是 Windows 在其行尾中的字符,但 Unix 没有)。bcarlso指出了这一点。运行dos2unix脚本以对其进行排序。在 bash 脚本中分配变量时,
=符号周围不能有空格。scibuff抓住了那个。下面被解释为尝试使用参数运行命令
FILES(不存在)= "/bowtie..."。FILES = "/bowtie-0.12.7-win32/bowtie-0.12.7/output_635_25bp/*"而以下解释为分配
"/bowtie..."给变量FILES:FILES="/bowtie-0.12.7-win32/bowtie-0.12.7/output_635_25bp/*"
回答by scibuff
try
尝试
FILES=/bow.../*
for f in $FILES
do
echo "hello world"
done
i.e. no spaces around ' = '
即“=”周围没有空格
回答by chris2k
Try to use the find-command
尝试使用查找命令
for i in `find /bow.../ -type f`
do
echo "hello world"
done
because ls will return directories too.
因为 ls 也会返回目录。

