脚本在 Mac 上运行但在 Ubuntu 上不运行

nic*_*coX 5 bash shell-script

该脚本在 Mac 机器上执行并创建输出文件,但在 Ubuntu 机器上它会生成错误消息。Bash shell 用于两个实例。:

1 - /var
2 - /etc : 
1
: bad variable name: read: word
first_part(1).sh: 6: first_part(1).sh: Syntax error: newline unexpected (expecting ")")
Run Code Online (Sandbox Code Playgroud)

——

echo "To scan through the directories /var and /etc type 1 or 2: "
echo "1 - /var"
echo "2 - /etc : "
read word
case $word in
         1)
                find /var -type d -follow -ls | awk '{print $3, $5, $6, $11}' > var.txt
                echo "Your file containing /var information has been created."
                ;;
         2)
                find /etc -type d -follow -ls | awk '{print $3, $5, $6, $11}' > etc.txt
                echo "Your file containing /etc information has been created."
                ;;
         *)
                echo "Please insert a valid input"
                continue
                ;;

esac
Run Code Online (Sandbox Code Playgroud)

Ant*_*hon 8

如果您使用 执行该文件sh filename.sh,那么一个问题是,在您的 Ubuntu 系统上,这可能不会执行,bash而是其他一些 shell。在我的 Ubuntu 12.04 系统sh/bin/sh是软链接/bin/dash(使用d; 参见“Dash as /bin/sh”)。

您应该使用bash filename.sh, 或使用 shebang 行并使文件可执行 ( chmod +x filename.sh)。

#!/bin/bash
echo "To scan through the directories /var and /etc type 1 or 2: "
echo "1 - /var"
.
.
Run Code Online (Sandbox Code Playgroud)

将文件从 Mac 移动到 Ubuntu 时要检查的一件事是文件的换行符(使用od -c file_name),如果输出中有 '\r' 字符,但\n您不必进行转换,例如使用:

tr '\r' '\n' < file_name > new_file_name.

  • 如您所见 - 您的格式化文本在评论中看起来很糟糕!改为编辑您的帖子要好得多。 (2认同)
  • @nicoX 我建议您提出一个新问题,在那里说明 bash 的版本以及您提供的脚本的结果差异,包括格式正确的错误消息。我认为您可能在这里遇到了行尾问题。所以也给出`od -c filename.sh | 的输出 head -10` 在那个新问题中。 (2认同)