2012-06-08 37 views
1

我需要知道是否可以标记bash脚本行号,然后在保存的行号处重新启动该脚本。是否可以标记和保存特定的bash脚本行号,并重新启动脚本保存位置?

代码:

#!/bin/bash 
while read -r line; do #I'm reading from a big wordlist 
command1 using $line 
command2 using $line 
done 

具体来说,就是有自动编写脚本的当前$行号到一个单独的文本文件,以使脚本从指定的行号开始的方式,使如果我必须停止脚本,我将不必从头开始一切工作?

是否有意义?

非常感谢!

+0

这个文件只是像日志文件一样增长吗?是否可以选择使用尾巴? – Oliver

+0

我正在阅读的单词列表不会增长。但它相当大(20MB)。 – bobylapointe

+0

20 MB不是关键尺寸。这需要多长时间? – Oliver

回答

2

这可能会帮助:

#!/bin/bash 

TMP_FILE="/tmp/currentLineNumber"       # a constant 

current_line_count=0          # track the current line number 

processed_lines_count=0 

# Verify if we have already processed some stuff. 
if [ -r "${TMP_FILE}" ]; then 
    processed_lines_count=$(cat ${TMP_FILE}) 
fi 

while read -r line; do         # I 'm reading from a big wordlist 

    # Skip processing till we reach the line that needs to be processed. 

    if [ $current_line_count -le $processed_line_count ]; then 

     # do nothing as this line has already been processed 
     current_line_count=$((current_line_count+1))  # increment the counter 
     continue 

    fi 

    current_line_count=$((current_line_count+1)) 
    echo $current_line_count > ${TMP_FILE}    # cache the line number 

    # perform your operations 
    command1 using $line 
    command2 using $line 

done 
+0

它工作得很好。我真的觉得我已经吃过东西了。再次感谢您 – bobylapointe

+0

感谢您分享更新bobylapointe。很高兴知道解决方案符合目的。 – Santhosh

1

这应该工作:

#!/bin/bash 
    I=`cat lastline`; 
    A=0; 

    while read -r line; do 
      if [$A>=$I]; then 
       command1 using $line 
       command2 using $line 
       ((I++)) 
       echo "$I" > "lastline"; 
      fi; 
      ((A++)) 
    done 

记住,你将不得不删除lastLine所,如果你想重新开始。 :-)

+0

我会试一试,非常感谢您抽出时间了解我的问题并向我提供解决方案Oliver。 – bobylapointe

1

唯一bash的解决方案是好的,但你可以通过使用其他工具,以简化您重新启动获得更好的性能。就像你的问题中的脚本一样,下面的代码将stdin上的单词列表。

#!/bin/sh 

# Get the current position, or 0 if we haven't run before 
if [ -f /tmp/processed ]; then 
    read processed < /tmp/processed 
else 
    processed=0 
fi 

# Skip up to the current position 
awk -v processed="$processed" 'NR > processed' | while read -r line; do 

    # Run your commands 
    command1 using $line 
    command2 using $line 

    # Record our new position 
    processed=$((processed + 1)) 
    echo $processed > /tmp/processed 

done 

哦,和我写这个的方式是Bourne shell兼容的,所以它不需要bash。