在 Windows 7 上的 cygwin 中运行 bash 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14598753/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:16:40  来源:igfitidea点击:

running bash script in cygwin on windows 7

bashwindows-7cygwin

提问by peter

I am trying to run the below bash script in cygwin on windows 7

我正在尝试在 Windows 7 上的 cygwin 中运行以下 bash 脚本

REPEATTIMES=""

if [ $# = 0 ]; then

    echo "Usage: fetch topN repeatTimes"
    exit 1
fi

for (( i=1; i<=$REPEATTIMES; i++ ))
do
    echo "ITERATION: $i"
    echo "GENERATING"

    log=thelogs/log 

    bin/nutch generate crawl/segment -topN 10 > $log
    batchId=`sed -n 's|.*batch id: \(.*\)||p' < $log`

    echo "batch id: $batchId "

    # rename log file by appending the batch id
    log2=$log$batchId
    mv $log $log2
    log=$log2

    echo "FETCHING"
    bin/nutch fetch crawl/segments/$batchId >> $log

    echo "PARSING"
    bin/nutch parse crawl/segments/$batchId >> $log


    echo "UPDATING DB"
    bin/nutch updatedb crawl/crawldb crawl/segments/$batchId >> $log

    echo "Done "

done


But when i run it i get the error :

但是当我运行它时,我收到错误:

line 11 :syntax error near unexpected token '$'\r'

line 11 :'for (( i=1; i<= REPEATTIMES; i++ ))

The script works fine on a ubuntu server. But i need to run it now on a windows machine.

该脚本在 ubuntu 服务器上运行良好。但我现在需要在 Windows 机器上运行它。

采纳答案by EJK

The latest version of Cygwin seems to only support files in Unix format (i.e. with \n for newlines as opposed to the DOS/Windows \r\n newline).

最新版本的 Cygwin 似乎只支持 Unix 格式的文件(即用 \n 表示换行符,而不是 DOS/Windows \r\n 换行符)。

To fix this, run the /bin/dos2unix.exe utility, giving your script as the argument to the command:

要解决此问题,请运行 /bin/dos2unix.exe 实用程序,将您的脚本作为命令的参数:

e.g. /bin/dos2unix.exe myScript.sh

This will convert it to Unix format and you then should be able to run it.

这会将其转换为 Unix 格式,然后您应该能够运行它。

回答by William

If you can't fix all your scripts, you should be able to modify the EOL behavior in Cygwin by setting an option to ignore CRs:

如果您无法修复所有脚本,您应该能够通过设置忽略 CR 的选项来修改 Cygwin 中的 EOL 行为:

set -o igncr

If you add this to your .bash_profile, it will be globally set by default when you login:

如果你把它添加到你的 .bash_profile 中,它会在你登录时默认全局设置:

export SHELLOPTS
set -o igncr

You can also do this per script internally by putting this line just after the #! line:

您也可以通过将这一行放在 #! 线:

(set -o igncr) 2>/dev/null && set -o igncr; # this comment is required

You need the comment to ignore the CR in that line which is read before the option takes effect.

您需要注释以忽略在选项生效之前读取的该行中的 CR。