Princey Princey - 4 months ago 14
Bash Question

Can't run interactive hashcat inside a while read loop

I am trying to run hashcat in a bash script multiple times in a loop. The issue that I'm having it that, because hashcat is interactive, the script executes it multiple times over. I would like to run the first hashcat command and, only when that finishes, the second one should run.

Script example:

while read dict
do
hashcat -m 0 -a 0 hashfile.hash $dict
done < dictionary_paths


Also, what about nested while loop?

For example:

while read rule_right
do
while read rule_left
do
hashcat -m 0 -a 1 hashfile.hash dict.lst dict.lst --rule-right=$rule_right --rule-left=$rule_left
done < $rule_left_file
done < $rule_right_file

Answer

The immediate answer here is to use a file descriptor other than stdin:

while IFS= read -r dict <&3; do
    hashcat -m 0 -a 0 hashfile.hash "$dict" # assuming dict is just one argument
done 3< dictionary_paths

The 3< means we open dictionary_paths on FD 3, and then the read ... <&3 redirects FD 3 to stdin during the read operation itself. Consequently, FD 0 -- stdin -- remains directed to its original source (such as a terminal) during the script's operation.


For a nested loop, use a different FD at each level:

while IFS= read -r rule_right <&3; do
    while IFS= read -r rule_left <&4; do
        hashcat -m 0 -a 1 hashfile.hash dict.lst dict.lst \
                --rule-right="$rule_right" --rule-left="$rule_left"
    done 4<"$rule_left_file"
done 3<"$rule_right_file"