我的bash脚本迭代文件有什么问题

时间:2012-02-08 13:48:39

标签: bash freebsd

我有这个bash脚本:

#!/bin/bash

file="release-candidate-1.0.tar.gz"
patch_base="patch-1.0."
patch_extension=".tar.gz"
i="1"

while [ -f $file ]
do
    echo $file
    file="${patch_base}${i}${patch_extension}"
    i=$((i+1))
done

运行脚本时我得到:

# ./script.sh
file=release-candidate-1.0.tar.gz: Command not found.
path_base=patch-1.0.: Command not found.
patch_extension=.tar.gz: Command not found.
i=1: Command not found.
file: Undefined variable.
#

我做错了什么?

3 个答案:

答案 0 :(得分:1)

我建议删除等号周围的空格:

file="release-candidate-1.0.tar.gz"
patch_base="patch-1.0."
patch_extension=".tar.gz"
i="1"

直到你的剧本令人满意,你可以运行它,例如与

/bin/bash -vx script.sh

答案 1 :(得分:1)

bash要求变量赋值不要用空格分隔'='。它必须全部一起运行,即

#!/bin/bash

file="release-candidate-1.0.tar.gz"
patch_bas="patch-1.0."
patch_extension=".tar.gz"
i="1"

while [ -f $file ]
do
    echo $file
    file="${patch_base}${i}${patch_extension}"
    i=$((i+1))
done

但是,还有更多

测试一系列补丁的更典型方法是

for i in {1..10} ; do
   file="${patch_base}${i}${patch_extension}"
   if [ -f ${file} ] ; then
      echo "Found ${file}"
   else
      echo "NO ${file}"
   fi
done

您可以将{1..10}更改为您认为有用的任何范围。或者,如果范围中缺少某些数字,您只需键入要测试的值,即for i in 2 4 6 ; do

我希望这会有所帮助。

答案 2 :(得分:0)

好的,问题是我的机器上没有安装bash。傻:D

我安装了这样的bash:

portsnap fetch
portsnap extract update
cd /usr/ports/shells/bash
make install clean

然后使用这个bash脚本:

#!/usr/local/bin/bash

file="release-candidate-1.0.tar.gz";
patch_base="patch-1.0.";
patch_extension=".tar.gz";
last_patch=500;
got_all_files=1;

for (( i = 0; i <= $last_patch; i++))
do
    if [ $i -eq 0 ]
    then
        if [ ! -f $file ]
        then
            got_all_files=0;
        fi
    else
        file=$patch_base$i$patch_extension;
        if [ ! -f $file ]
        then
            got_all_files=0;
        fi
    fi
done

if [ $got_all_files -eq 0 ]
then
    echo "Missing files.";
    exit;
fi

file="release-candidate-1.0.tar.gz";

for (( i = 0; i <= $last_patch; i++))
do
    if [ $i -eq 0 ]
    then
        tar xzvpf $file
        ./install.sh
        ./services restart
    else
        file=$patch_base$i$patch_extension;
        tar xzvpf $file
        ./patch.sh
    fi
done