做循环。对第一条记录进行例外处理并像往常一样继续循环

时间:2014-02-10 12:52:03

标签: shell loops sed awk while-loop

我做了while循环,它将获取文件名和运行命令。很标准的东西。我想要做的是对我提供给Do While循环的文件进行排序,然后对第一个文件进行排序,我想运行一个command1,其余的则运行command2

find  $dir -iname  "$search*" |<some commands> | sort -nr
while read filename; do
 # if its the very 1st file .  head - 1 would do that 

echo "command1 > log > 2>&1& " >> appendfile 
echo "if [ $? != 0 ] then ; exit 1 fi " >> appendfile

# for all other files do this 
echo "command1 > log > 2>&1& " >> appendfile 

现在你也看到了我在做什么。我正在写appendfile.ksh的东西,稍后会运行。我选择第一个文件最小的文件作为“测试文件”来运行command1。如果作业异常退出,则继续处理剩余的文件 我正在尝试如何容纳第一个进入Do While的文件,并进行一些特殊的处理

3 个答案:

答案 0 :(得分:4)

#!/bin/bash
f=1
find . -name "*.txt" | while IFS= read -r filename
do
   if [ $f -eq 1 ]; then
      echo First file
   else
      echo Subsequent file
   fi
   ((f++))
done

答案 1 :(得分:2)

你可以这样做:

first=""

while read filename; do
  if [ -z "$first" ]; then
     first="$filename"
     # if its the very 1st file .  head - 1 would do that 
     echo "command1 > log > 2>&1& " >> appendfile 
     echo "if [ $? != 0 ] then ; exit 1 fi " >> appendfile
  else
     # for all other files do this 
     echo "command2 > log > 2>&1& " >> appendfile 
  fi
done < <(find "$dir" -iname "$search*" | <some commands> | sort -nr)

答案 2 :(得分:1)

while循环开始之前,使用复合命令分别使用第一个文件名。这样做的好处是允许您使用单个重定向将复合命令的所有输出附加到appendfile,而无需单独重定向每个echo命令。请务必注意每个命令的更正重定向语法。

find  $dir -iname  "$search*" |<some commands> | sort -nr | {
    # This read gets the first line from the pipeline
    read filename
    echo "command1 > log 2>&1 "
    echo "if [ $? != 0 ] then ; exit 1 fi "

    # These reads will get the remaining lines
    while read filename; do
        echo "command2 > log2 2>&1 "
        echo "if [ $? != 0 ] then ; exit 1 fi "
    done
}  >> appendfile   # If appendfile isn't written to before, you can just use >

还有一点未经请求的建议:你可以通过

来缩短你的脚本
command1 > log 2>&1 || exit 1

而不是使用明确的if语句。