通常我们在执行shell脚本的时候会遇到类似下面的错误,而事实上脚本没有任何问题,很多人会卡在这一步很久,其实有可能是编码导致的回车符不一致引起的:
ERROR:
$'\r': command not found
^M: bad interpreter
No such file or directory
这种情况有可能发生在脚本在windows环境下编写或修改,然后上传到Linux服务器执行时报错,可以使用dos2unix命令将DOS编码转为UNIX编码,同样也可以使用unix2dos命令将UNIX编码转为DOS编码。
#DOS编码转为UNIX编码dos2unix filename #UNIX编码转DOS编码unix2dos filename #有些机器上没有安装dos2unix命令,也可以使用vim命令修改编码vim filename#vim打开文件后执行下面的命令即可转为unix编码:set fileformat=unix
类似的还有 mac2unix, unix2mac 适用于mac系统和unix系统编码转换;
例子:
wyk_csdh.sh
#!/bin/bashBASEDIR="`dirname $0`"name=$1company=$2 echo $BASEDIRecho $nameecho $company
这个shell在windows环境下编辑,上传到linux环境执行后会报错:
使用cat -v命令可以看到非打印的特殊字符:
cat --helpUsage: cat [OPTION]... [FILE]...Concatenate FILE(s), or standard input, to standard output. -A, --show-all equivalent to -vET -b, --number-nonblank number nonempty output lines, overrides -n -e equivalent to -vE -E, --show-ends display $ at end of each line -n, --number number all output lines -s, --squeeze-blank suppress repeated empty output lines -t equivalent to -vT -T, --show-tabs display TAB characters as ^I -u (ignored) -v, --show-nonprinting use ^ and M- notation, except for LFD and TAB --help display this help and exit --version output version information and exit
使用dos2unix转为unix编码:
使用vim命令转换编码:
希望本文对你有帮助,请点个赞鼓励一下作者吧~ 谢谢!