【问题标题】:Scripting with Variables not working?使用变量编写脚本不起作用?
【发布时间】:2014-05-03 10:47:26
【问题描述】:

我正在尝试学习一些 unix,并且正在尝试编写一些基本变量的脚本,知道为什么在我进行数学运算时这不起作用吗?

> vi math 
A=5
B=10
let C=A+B
let D=B-A
let E=A*B
let F=A/B
echo $A $B $C $D $E $F

这是显示的内容。

math: 4: math: let: not found
math: 5: math: let: not found
math: 6: math: let: not found
math: 7: math: let: not found
5 10

【问题讨论】:

  • 什么不起作用?您应该使用 bash 使用 bash ./math 运行它
  • 现代 POSIX 标准的数学运算方法是 C=$((A+B))let 是过去时代的遗物。
  • ...另外,“不起作用”并不是很有用。如果您准确地描述了它的作用,那会让人们更有帮助。
  • 您的输出与我在使用dash 时看到的相同。你能显示输出:bash math,然后是sh math,然后是dash math?我希望sh math 的输出与dash math 的输出相同。
  • 是的,当我做 Bash 数学时它可以工作... > sh math math: 4: math: let: not found math: 5: math: let: not found math: 6: math: let :未找到数学:7:数学:让:未找到 5 10 > bash 数学 5 10 15 5 50 0 > 破折号数学数学:4:数学:让:未找到数学:5:数学:让:未找到数学:6 : math: let: not found math: 7: math: let: not found 5 10

标签: bash shell variables unix scripting


【解决方案1】:

/bin/sh 是 Bash(Mac OS X 10.9.2 Mavericks)的系统上,我得到:

$ cat math
A=5
B=10
let C=A+B
let D=B-A
let E=A*B
let F=A/B
echo $A $B $C $D $E $F
$ sh math
5 10 15 5 50 0
$ bash math
5 10 15 5 50 0
$ ksh math
5 10 15 5 50 0
$ dash math
math: 3: math: let: not found
math: 4: math: let: not found
math: 5: math: let: not found
math: 6: math: let: not found
5 10
$ hsh math
math: let: not found
math: let: not found
math: let: not found
math: let: not found
5 10
$

hsh 是作为另一个名称安装的 Heirloom Bourne Shell。)

这意味着sh mathbash math 都按照您的意图进行算术运算。您是否在具有与 /bin/sh 不同的外壳的机器上(可能是伪装的 dash 而您在 Ubuntu 上)?

【讨论】:

  • 这样做 #!/bin/sh A=5 B=10 let C=A+B let D=BA let E=A*B let F=A/B echo $A $B $ C $D $E $F 但我还是不行。
  • 您能否提供有关您的环境的更多详细信息?哪个操作系统和版本?哪个版本的 Bash? (使用bash --version 找出答案。/bin/sh --version 是否说同样的事情?)当您说“它不工作”时,您看到的错误消息到底是什么?请将这些详细信息添加到问题中,而不是此处的 cmets。将来,请特别包括您在前面的问题中看到的确切错误消息;这意味着我们必须减少对您所看到的问题的猜测。
  • GNU bash,版本 4.2.25(1)-release (x86_64-pc-linux-gnu) 用出现的内容编辑我的问题。
猜你喜欢
  • 1970-01-01
  • 2019-04-06
  • 1970-01-01
  • 1970-01-01
  • 2020-12-24
  • 1970-01-01
  • 2022-09-28
  • 2017-08-27
  • 2023-03-05
相关资源
最近更新 更多