我需要知道是否可以标记bash脚本行号,然后在保存的行号处重新启动该脚本。
代码:
#!/bin/bash
while read -r line; do #I'm reading from a big wordlist
command1 using $line
command2 using $line
done
具体来说,有没有办法将脚本的当前$行号自动写入单独的文本文件中,以便脚本从指定的行号开始,这样我就不必从头开始一切如果我不得不停止脚本?
有意义吗?
非常感谢!
答案 0 :(得分: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
答案 1 :(得分: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。 : - )
答案 2 :(得分:1)
仅限bash的解决方案很不错,但您可以通过使用其他工具简化重新启动来获得更好的性能。与您问题中的脚本一样,以下内容采用stdin上的wordlist。
#!/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。