我在我的一台 ubuntu 虚拟机中编写了一个 sh 脚本,该脚本工作正常,但是当我尝试在其他虚拟机中运行它时,它不起作用。两个虚拟机应该相同。
bash --version
两个虚拟机都会回复:
GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
和
lsb_release -a
,两人也回复:
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 14.04.3 LTS
Release: 14.04
Codename: trusty
我的
security_steps.sh
脚本看起来像这样:
#!/bin/sh
set -e
if ! [ -f svn_up_action.sh ]; then
echo "svn_up_action.sh is missing. Please make sure it is in the same directory as this script."
exit
fi
当我这样做时:
sudo sh security_steps.sh
,控制台错误:
: not foundeps.sh: 6: security_steps.sh:
security_steps.sh: 7: set: Illegal option -
如何找出非工作 shell 的 VM 发生了什么?我感觉贝壳有些不同。我感谢您的帮助!
这几乎肯定意味着您的文件有 DOS 换行符 - 因此,在末尾隐藏了 CR 字符。
因此,
set -e
变为 set -e$'\r'
(使用 bash 特定的语法来表示 CR 字符),这不是一个有效的选项。
这也解释了
: not found
,因为 CR 会将光标重置到行的开头,通过使 sh: commandname: not found
代替将光标移动到行首的操作来截断 commandname
形式的错误消息线。
我在 Windows 上运行 *.sh 文件时抛出了这个问题(通过 GitBash)。
我必须将行结尾更改为 UNIX/OSX 格式。
在 Windows 中:
choco install dos2unix
dos2unix file.sh
在 Linux 中:
sudo apt install dos2unix
dos2unix file.sh
dos2unix 将文件转换为 Unix 类型。
执行此操作后,尝试再次运行应用程序或文件。
如果您因为在 Windows 计算机上触摸文件而遇到此问题,Notepad++ 是您的朋友。
检查
视图 > 显示符号 > 显示所有字符
寻找
CR
LF
行结尾,而不是 LF
行结尾!
解决
搜索 > 替换 (Ctrl+H)
确保搜索模式设置为
Extended
\r\n
并替换为 \n
我遇到了同样的错误,
后来我发现这些问题是因为我的shell脚本文件从Windows机器移动到Linux机器(可能有格式或编码错误)。
所以我已经在 Linux 机器本身中创建了该文档。解决了这个问题。
这个“五月”对少数人有帮助,我发布这个是因为它对我有用。
您可以使用以下命令,它将删除隐藏的 CR 字符
sed -i 's/\r$//' filename
这是因为行尾序列(
CRLF
和LF
)
根本原因是 Windows 使用 \r\n
作为行尾,而 *nix 仅使用 \n
。
在 Windows 中,将行尾顺序设置为
LF
。
您可以在 VSCode 中轻松选择它。