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: $'
': command not found
runbundler.sh: line 7: $'
': command not found
runbundler.sh: line 13: $'
': command not found
runbundler.sh: line 16: $'
': 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 格式。
ff
是fileformat
的缩写,因此也可以输入 :set fileformat=unix
。
这时 :set ff
查看会得到修改后的结果 fileformat=unix
。
然后再执行脚本就不会出现上面的错误了!
(全文完)
参考资料
[1] 解决执行脚本报syntax error: unexpected end of file或syntax error near unexpected token `fi'错误的问题 https://blog.csdn.net/u012453843/article/details/69803244/
本文作者 :phillee
发表日期 :2021年6月1日
本文链接 :https://www.cnblogs.com/phillee/p/14838190.html
版权声明 :自由转载-非商用-非衍生-保持署名(创意共享3.0许可协议/CC BY-NC-SA 3.0)。转载请注明出处!
限于本人水平,如果文章和代码有表述不当之处,还请不吝赐教。