[英]shell script variable use
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. 现在我收到以下错误MY_VAR未找到,[6:未找到,所以我假设一个相当noobish错误。 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.
我觉得这个逻辑听起来很简单只是一个简单的语法错误我正在通过我认为它可能在声明中的两个错误的外观而在某处。
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): 这是用Bash(或ksh)重写的脚本:
my_var=6
until ((my_var == 0))
do
dir/dir_$my_var.log # I have no idea what this is supposed to be
ps | grep "NAME_$my_var.ksh"
# check some things
if [[ $results = ok ]]
then
echo "program $my_var successful"
else
echo "program $my_var failure"
((my_var--))
fi
done
However: 然而:
for my_var in {6..1}
do
dir/dir_$my_var.log # I have no idea what this is supposed to be
ps | grep "NAME_$my_var.ksh"
# check some things
if [[ $results = ok ]]
then
echo "program $my_var successful"
else
echo "program $my_var failure"
fi
done
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). shell正在寻找命令
[6
(扩展$MY_VAR
),而不是[
(看看/usr/bin/[
- 它实际上是一个程序)。 You should also use -eq
to do numeric comparisons. 您还应该使用
-eq
进行数值比较。 =
should work ok here, but leading zeros can break a string comparison where a numeric comparison would work: =
应该在这里工作正常,但是前导零可以打破字符串比较,数字比较可以工作:
until [ "$MY_VAR" -eq 0 ]
The second problem is you have spaces in your variable assignment. 第二个问题是变量赋值中有空格。 When you write
MY_VAR = ...
the shell is looking for the command MY_VAR
. 当你写
MY_VAR = ...
,shell正在寻找命令MY_VAR
。 Instead write it as: 而是将其写为:
MY_VAR=`expr $MY_VAR - 1`
These answers directly answer your questions, but you should study Dennis Williamson's answer for better ways to do these things. 这些答案直接回答了你的问题,但你应该研究丹尼斯威廉姆森的答案,以便更好地做这些事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.