gpt4 book ai didi

bash - "bad variable name"使用 "read var"

转载 作者:行者123 更新时间:2023-11-29 09:10:06 25 4
gpt4 key购买 nike

我对 Linux shell 感到困惑。作为 Linux 新手,我可能会监督一些明显的事情。

我只想运行以下脚本:

#!/bin/bash
echo "Type some Text:"
read var
echo "You entered: "$var

情况是这样的:

  • 在 Windows 上的 VirtualBox 中安装了 Ubuntu Server 14.04
  • 用这个安装它 packages
  • 安装在/media/buff 上的 SAMBA
  • 脚本在/media/buff/ShellScript/test.sh
  • 通过“sudo chmod a+x/media/buff/ShellScript/test.sh”使其可执行
  • 其余默认
  • 我在 Windows 上使用 PSPad 来编辑脚本文件

read关于破折号,但我不明白。以下是一些变体:

使用sh启动

user@Ubuntu:/media/buff/ShellScript$ sh test.sh
Type some Text:
:bad variable nameread var
You entered:

使用 bash 启动:

user@Ubuntu:/media/buff/ShellScript$ bash test.sh
Type some Text:
': Ist kein gültiger Bezeichner.var (means no valid identifyier)
You entered:

将脚本中的Shebang改为"#!/bin/sh",使用sh启动

user@Ubuntu:/media/buff/ShellScript$ sh test.sh
Type some Text:
:bad variable nameread var
You entered:

我现在在 Internet 上搜索了几个小时,我认为脚本本身没问题,但缺少一些环境设置。我使用“sudo dpkg-reconfigure dash”将 dash 设置为默认 shell(我认为这是 ubuntu 默认的)

悲伤的 Pandas :)

最佳答案

在 shell 脚本中你的行末尾很可能有回车符(CR,'\r'),所以变量正试图被读入 var\r 而不是 var。这就是为什么您的错误消息毫无意义。类似的错误应该look like this :

run.sh: 3: export: [... the variable name]: bad variable name

在您的情况下,bash 会抛出错误,因为 var\r 由于回车而对于变量名是非法的,因此它会打印

test.sh: 3: read: var\r: bad variable name

但是 \r 跳转到行首,覆盖错误消息的开头。

可以使用 dos2unix 实用程序从行尾删除回车符。

关于bash - "bad variable name"使用 "read var",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33320452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com