" bash:数组和错误替换"在.sh文件中使用do时

时间:2014-07-17 16:34:10

标签: arrays linux bash shell

我想创建一个运行某个程序并检查它们是否已启动的脚本,不幸的是我收到了一些错误,我不知道为什么:

#!/bin/sh
# start file

c[0] = 'foo'
c[1] = 'mickey'
c[2] = 'mouse'

echo "Launching..."

for i in 0 1 2; do
        echo "Starting ${c[i]}"
        ${c[i]}
        ps cax | grep ${c[i]}
        if [ $? -eq 0 ]; then
          echo "${c[i]} is running"
        else
        {
            echo "${c[i]} is not running"
            ${c[i]}
        } 
        fi
done

echo "launch completed."

当我尝试运行它时,shell不识别命令名称,并且我也收到错误

for i in 0 1 2; do

表示“不良替代”。

你能解释一下这个脚本我错在哪里吗?提前谢谢。

----更新----

感谢我们真诚的回答,我根据您的建议修改了我的脚本:

#!/bin/bash
# start file


echo "Launching..."

for i in foo mickey mouse; do
        echo "Starting $i"
        $i
        ps cax | grep $i
        if [ $? -eq 0 ]; then
          echo "$i is running"
        else
            echo "$i is not running"
            $i
        fi
done

echo "launch completed."

再次感谢! 的Fabrizio

3 个答案:

答案 0 :(得分:2)

好的,这里有一些错误,让我们从一开始就经历这些错误:

c[0] = 'foo'
c[1] = 'mickey'
c[2] = 'mouse'

c未定义,分配中没有空格:

c=()
c[0]='foo'
c[1]='mickey'
c[2]='mouse'

有关

    echo "Starting ${c[i]}"
    ${c[i]}
    ps cax | grep ${c[i]}
    if [ $? -eq 0 ]; then
      echo "${c[i]} is running"
    else
    {
        echo "${c[i]} is not running"
        ${c[i]}
    } 
    fi

您需要引用$ {c [$ i]}来访问索引,$ c [i]引用基于字符i的索引,而不是变量。

    echo "Starting ${c[$i]}"
    ${c[$i]}
    ps cax | grep ${c[$i]}
    if [ $? -eq 0 ]; then
      echo "${c[$i]} is running"
    else
    {
        echo "${c[$i]} is not running"
        ${c[$i]}
    } 
    fi

最后:

    else
    {
        echo "${c[$i]} is not running"
        ${c[$i]}
    } 
    fi

Bash没有使用大括号if / else,摆脱它们

    else
        echo "${c[$i]} is not running"
        ${c[$i]}
    fi

全部完成。

答案 1 :(得分:1)

您需要更改

c[0] = 'foo'
c[1] = 'mickey'
c[2] = 'mouse'

c[0]='foo'
c[1]='mickey'
c[2]='mouse'

答案 2 :(得分:1)

请查看此代码。使用0 1 2迭代数组是不好的,因为你可能不知道数组的大小。最好使用$ {c [@]},它将包含数组的所有元素。这将是更有活力和更好的

 #!/bin/sh
 # start file
 c=(foo mickey mouse)

  echo "Launching..."
  //below one to execute your foo or micckyor mouse command
  $i
  for i in ${c[@]}; do
    echo "Starting $i"
    ps cax | grep $i
    if [ $? -eq 0 ]; then
      echo "$i is running"
    else
    {
        echo "$i is not running"
         //below one to execute your foo or micckyor mouse command
         $i
    }
    fi
 done

 echo "launch completed."