在 Bash 变量赋值中找不到命令错误 [英] Command not found error in Bash variable assignment

查看:25
本文介绍了在 Bash 变量赋值中找不到命令错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 test.sh 的脚本:

I have this script called test.sh:

#!/bin/bash
STR = "Hello World"
echo $STR

当我运行 sh test.sh 我得到这个:

when I run sh test.sh I get this:

test.sh: line 2: STR: command not found

我做错了什么?我在网上查看非常基本/初学者的 bash 脚本教程,这就是他们所说的声明变量的方式......所以我不确定我做错了什么.

What am I doing wrong? I look at extremely basic/beginners bash scripting tutorials online and this is how they say to declare variables... So I'm not sure what I'm doing wrong.

我使用的是 Ubuntu Server 9.10.是的,bash 位于 /bin/bash.

I'm on Ubuntu Server 9.10. And yes, bash is located at /bin/bash.

推荐答案

= 符号周围不能有空格.

You cannot have spaces around the = sign.

当你写作时:

STR = "foo"

bash 尝试运行带有 2 个参数(字符串 =foo)的名为 STR 的命令

bash tries to run a command named STR with 2 arguments (the strings = and foo)

当你写作时:

STR =foo

bash 尝试使用 1 个参数(字符串 =foo)运行名为 STR 的命令

bash tries to run a command named STR with 1 argument (the string =foo)

当你写作时:

STR= foo

bash 尝试运行命令 foo,并在其环境中将 STR 设置为空字符串.

bash tries to run the command foo with STR set to the empty string in its environment.

我不确定这是否有助于澄清或仅仅是混淆,但请注意:

I'm not sure if this helps to clarify or if it is mere obfuscation, but note that:

  1. 第一个命令完全等同于:STR "=";"foo",
  2. 第二个与STR=foo"相同,
  3. 和最后一个等价于 STR="";foo.

sh 语言规范的相关部分,第 2.9.1 节 状态:

一个简单的命令"是一系列可选的变量赋值和重定向,以任何顺序,可选地后跟单词和重定向,以控制运算符终止.

A "simple command" is a sequence of optional variable assignments and redirections, in any sequence, optionally followed by words and redirections, terminated by a control operator.

在这种情况下,word 是 bash 将要运行的命令.任何包含 = 的字符串(在字符串开头以外的任何位置)不是重定向,并且 = 之前的字符串部分是有效的变量名是一个变量赋值,而任何不是重定向或变量赋值的字符串都是一个命令.在 STR = "foo" 中,STR 不是变量赋值.

In that context, a word is the command that bash is going to run. Any string containing = (in any position other than at the beginning of the string) which is not a redirection and in which the portion of the string before the = is a valid variable name is a variable assignment, while any string that is not a redirection or a variable assignment is a command. In STR = "foo", STR is not a variable assignment.

这篇关于在 Bash 变量赋值中找不到命令错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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