shell脚本变量的使用
我将开始讨论重点:
MY_VAR=6
until [$MY_VAR = 0]
do
dir/dir_$MY_VAR.log
ps | grep "NAME_$MY_VAR.ksh"
check some things
if [results = ok]
echo "program $MY_VAR sucessful"
else
echo "program $MY_VAR failure"
MY_VAR = `expr $MY_VAR - 1`
done
现在我收到以下错误 MY_VAR not found 和 [6: not found,所以我假设这是一个相当菜鸟的错误。我觉得逻辑足够合理,只是我在某个地方犯了一个简单的语法错误,从我认为可能出现在声明中的两个错误的外观来看。
I'll get to the meat and bones:
MY_VAR=6
until [$MY_VAR = 0]
do
dir/dir_$MY_VAR.log
ps | grep "NAME_$MY_VAR.ksh"
check some things
if [results = ok]
echo "program $MY_VAR sucessful"
else
echo "program $MY_VAR failure"
MY_VAR = `expr $MY_VAR - 1`
done
Now I am getting the following errors MY_VAR not found and [6: not found, so I'm assuming a rather noobish mistake. I feel the logic is sound enough just a simple syntax error I am making somewhere by the looks of the two errors I think it could be in the declaration.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
[
之后和]
之前需要有一个空格,因为[
实际上是一个命令而不是分隔符。这是用 Bash(或 ksh)重新编写的脚本:
但是:
You need to have a space after
[
and before]
since[
is actually a command and not a delimiter.Here is your script re-written in Bash (or ksh):
However:
您的两个错误是由以下原因引起的:
until [$MY_VAR = 0]
MY_VAR = $(expr $MY_VAR - 1)
[我使用 $() 而不是反引号,因为我无法在代码部分添加反引号]
第一个问题是方括号周围缺少空格 - 两端。 shell 正在寻找命令
[6
(展开$MY_VAR
后),而不是[
(看看/usr /bin/[
- 它实际上是一个程序)。您还应该使用-eq
进行数字比较。=
在这里应该可以正常工作,但是前导零可能会破坏数字比较可以工作的字符串比较:第二个问题是变量赋值中有空格。当您编写
MY_VAR = ...
时,shell 会查找命令MY_VAR
。相反,请将其写为:这些答案直接回答您的问题,但您应该研究丹尼斯·威廉姆森的答案,以获得更好的方法来完成这些事情。
Your two errors are caused by:
until [$MY_VAR = 0]
MY_VAR = $(expr $MY_VAR - 1)
[I've used $() instead of backticks because I couldn't get backticks into the code section]
The first problem is the lack of spaces around the square brackets - on both ends. The shell is looking for the command
[6
(after expanding$MY_VAR
), instead of[
(have a look at/usr/bin/[
- it's actually a program). You should also use-eq
to do numeric comparisons.=
should work ok here, but leading zeros can break a string comparison where a numeric comparison would work:The second problem is you have spaces in your variable assignment. When you write
MY_VAR = ...
the shell is looking for the commandMY_VAR
. Instead write it as:These answers directly answer your questions, but you should study Dennis Williamson's answer for better ways to do these things.