1

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

代码:

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

具体来说,有没有办法将脚本的当前 $line 号自动写入单独的文本文件,以便脚本从指定的行号开始,这样我就不必从头开始一切,以防万一必须停止脚本?

是否有意义?

非常感谢你 !

4

3 回答 3

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
于 2012-06-08T16:02:16.547 回答
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

请记住,如果要重新启动,则必须删除最后一行。:-)

于 2012-06-08T15:50:06.887 回答
1

仅限 bash 的解决方案很好,但您可以通过使用其他工具来简化重新启动,从而获得更好的性能。就像您问题中的脚本一样,以下内容采用标准输入上的单词表。

#!/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。

于 2012-06-09T03:10:20.303 回答