Windows登录服务器CLI运行脚本出现 syntax error: unexpected end of file 错误的解决

时间:2023-12-04 10:51:02

0.前言

通常我们在编辑 Linux 服务器上的文件时,直接在 Linux 环境比较麻烦(当然熟练使用 VIM 的程序员除外哈哈),有时我们会使用 Windows 将文件编辑好再上传到服务器端,我用的是 Sublime text 。

1.问题描述与记录

编辑完脚本上传到服务器运行时,会出现语法错误,以下面的一小段脚本为例

#!/bin/bash
echo "updatedb..."
sudo updatedb BASE_PATH=$(dirname $(locate $0))
echo ${BASE_PATH} if [ $BASE_PATH == "TODO" ]
then
echo "please modify this script with the base path of your bundler installation";
exit;
fi EXTRACT_FOCAL=${BASE_PATH}/bin/extract_focal.pl
echo ${EXTRACT_FOCAL} echo "[- Done -]"
cv@cv: ~/bundler$ bash runbundler.sh
runbundler.sh: line 4: $'\r': command not found
runbundler.sh: line 7: $'\r': command not found
runbundler.sh: line 13: $'\r': command not found
runbundler.sh: line 16: $'\r': command not found
runbundler.sh: line 17: syntax error: unexpected end of file

2. 问题分析与解决

这里显示的两个问题都是因为我们的.sh文件为dos格式,在 dos/windows 系统中按一次回车键实际上输入的是CRLF ,即回车+换行。

而 Linux 系统一般只能执行 unix 格式的脚本,在 Linux/Unix 系统中按一次回车键实际上输入的是 LF ,即只有换行。

所以这里在 Windows 系统编辑的 sh 脚本文件每行都多了一个回车,当在 Linux 系统中运行时就会报错提示找不到相关命令。

我们可以查看该脚本的格式,在命令行使用 vim 打开脚本, ESC 进入命令输入模式。

输入 :set ff ,查看输出结果,比如我得到的是 fileformat=dos

此时我们可以使用:set ff=unix将 dos 格式更改为 unix 格式。

fffileformat的缩写,因此也可以输入 :set fileformat=unix

这时 :set ff 查看会得到修改后的结果 fileformat=unix

然后再执行脚本就不会出现上面的错误了!

(全文完)