“错误的变量名"使用"read var"; [英] "bad variable name" using "read var"

查看:256
本文介绍了“错误的变量名"使用"read var";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Linux shell感到困惑.可能是我监督了一些明显的Linux noob问题.

I am getting confused about Linux shells. It may be that I oversee something obvious as a Linux noob.

我只想运行以下脚本:

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

这里是情况:

  • 在Windows的VirtualBox中安装了Ubuntu Server 14.04
  • 使用此软件包
  • 安装
  • 安装在/media/buff上的SAMBA
  • 该脚本位于/media/buff/ShellScript/test.sh
  • 由"sudo chmod a + x/media/buff/ShellScript/test.sh"制成可执行文件
  • 其余为默认
  • 我正在Windows上使用PSPad编辑脚本文件
  • Installed Ubuntu Server 14.04 in a VirtualBox on windows
  • Installed it with this packages
  • A SAMBA mounted on /media/buff
  • The script is on /media/buff/ShellScript/test.sh
  • made executable by "sudo chmod a+x /media/buff/ShellScript/test.sh"
  • The rest is default
  • I am using PSPad on windows to edit the script file

阅读有关破折号的信息,但我听不懂. 以下是一些变体:

I read about the dash but I'm not getting it. Here are some variations:

使用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启动

Changed the Shebang in the script to "#!/bin/sh", Using sh to launch

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

我现在在Internet上搜索了几个小时,我认为脚本本身还可以,但是缺少一些环境设置. 我使用"sudo dpkg-reconfigure破折号"将破折号设置为默认外壳(无论如何我还是认为它是ubuntu的默认设置)

I searched across the Internet for hours now and I assume, that the script itself is ok, but there are missing some environment settings. I used "sudo dpkg-reconfigure dash" to set dash as default shell (which I think is ubuntu default anyway)

熊猫脸:)

推荐答案

在shell脚本的行尾很可能有回车符(CR,'\r'),因此该变量正试图读入var\r代替var.这就是为什么您的错误消息没有意义的原因.类似的错误应看起来像这样:

There are most probably carriage returns (CR, '\r') at the end of your lines in the shell script, so the variable is trying to be read into var\r instead of var. This is why your error message is meaningless. A similar error should look like this:

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

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

In your case bash throws an error because var\r is illegal for a variable name due to the carriage return, so it prints

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

,但是\r跳到该行的开头,覆盖错误消息的开头.

but the \r jumps to the beginning of the line, overwriting the start of the error message.

可能通过使用dos2unix实用程序,删除回车,以从行尾返回.

Remove the carriage returns fom the ends of lines, possibly by using the dos2unix utility.

这篇关于“错误的变量名"使用"read var";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆