Script de shell simples incapaz de passar por milhares de arquivos; começa bem, mas lança "EOF inesperado enquanto procura `"` "correspondente depois de algum tempo

Script de shell simples incapaz de passar por milhares de arquivos; começa bem, mas lança "EOF inesperado enquanto procura `"` "correspondente depois de algum tempo

ShellScript em questão

Deixe-me explicar o que estou tentando fazer, por exemplo, para que você possa entender melhor. Digamos que eu tenha 100 arquivos .torrent em um diretório. 2 deles baixarão xxx.epub e yyy.epub respectivamente, se adicionados a um cliente bittorrent, mas não sei quais 2 entre 100.

Então, o que meu script faz é (1) findpassar por todos os arquivos .torrent pwde passar cada arquivo .torrent, conforme ele aparece, para transmission-showo qual analisará o arquivo .torrent e gerará metadados em formato legível por humanos. Em seguida, usaremos awkpara obter o nome do arquivo que o arquivo torrent irá baixar e executá-lo no list.txt que contém os nomes dos arquivos que estamos procurando, ou seja, xxx.epub e yyy.epub.

Arquivo: findtor-array.sh

#! /bin/bash
#
# Search .torrent file based on 'Name' field.
#
# USAGE:
# cd ~/myspace # location of .torrent files
# Run `findtor ~/list.txt` (if `findtor.sh` is placed in `~/bin` or `~/.local/bin`)

# Turn the list of file names from ~/list.txt (or any file passed as argument) into an array
readarray -t FILE_NAMES_TO_SEARCH < "$1"

# For each file name from the list...
for FILE_NAME in "${FILE_NAMES_TO_SEARCH[@]}"
do
    # In `pwd` and 1 directory-level under, look for .torrent files and search them for the file name
    find . -maxdepth 2 -name '*.torrent' -type f -exec bash -c "transmission-show \"\$1\" | awk '/^Name\: / || /^File\: /' | awk -F ': ' '\$2 ~ \"$FILE_NAME\" {getline; print}'" _ {} \; >> ~/torrents.txt

    # The `transmission-show` command included in `find`, on it own, for clarity:
    # transmission-show xxx.torrent | awk '/^Name: / || /^File: /' | awk -F ': ' '$2 ~ "SEARCH STRING" {getline; print}'
done

Acho que o processo é simples e estou fazendo certo (só que não há verificações, eu sei). Mas de alguma forma toda a tarefa parece demais para o script, pois depois de executá-lo, depois de algum tempo ele começa a lançar esses erros continuamente até que eu Ctrl+ C:

_: -c: line 0: unexpected EOF while looking for matching `"'
_: -c: line 1: syntax error: unexpected end of file

Esses são problemas de "escalação"? O que estou perdendo e o que posso fazer para consertar?

Responder1

FILE_NAMEestá sendo passado diretamente bash -cna -execopção do seu findcomando. Isso causa problemas se FILE_NAMEcontiver aspas/código shell. Na verdade,código arbitrário pode ser executado. Exemplo: neste caso específico, o arquivo de entrada pode conter uma linha'; echo "run commands";'

Em vez disso, passe o loop var to bash -ccomo um parâmetro posicional. por exemplo:

find . -maxdepth 2 -name '*.torrent' -type f -exec sh -c '
transmission-show "$2" |
awk -v search="$1" '\''/^Name: / {name = substr($0,7)} /^File: / && name ~ search {print; exit}'\' \
_ "$FILE_NAME" {} \;

Além disso, parece ineficiente fazer um loop em todos os termos de pesquisa de cada arquivo. Considere fazer um loop nos arquivos e pesquisar com grep -f file:

find . -maxdepth 2 -name '*.torrent' -type f -exec sh -c '
file=$1
shift
if transmission-show "$file" | head -n 1 | cut -d" " -f2- | grep -q "$@"; then
    printf "%s\n" "$file"
fi' _ {} "$@" \;

ou sem find:

for file in *.torrent */*.torrent; do
    if transmission-show "$file" | head -n 1 | cut -d' ' -f2- | grep -q "$@"; then
        printf '%s\n' "$file"
    fi
done
  • O acima simplesmente passa todos os argumentos para grep, então o uso seria findtor -f ~/list.txtpegar padrões da lista, -Fpara strings fixas,, -e expressionetc.

Responder2

Com base nas sugestões de @Kusalananda, nas respostas (de @guest e @Jetchisel) eesta resposta detalhada de Kevin, eu descobri isso:

#! /bin/bash
#
# Search for 'Name' field match in torrent metadata for all .torrent files in
# current directory and directories 1-level below.
#
# USAGE e.g.:
# cd ~/torrent-files # location of .torrent files
# Run `~/findtor.sh ~/list.txt`

# Get one file name at a time ($FILE_NAME_TO_SEARCH) to search for from list.txt
# provided as argument to this script.
while IFS= read -r FILE_NAME_TO_SEARCH; do

    # `find` .torrent files in current directory and directories 1-level under
    # it. `-print0` to print the full file name on the standard output, followed
    # by a null character (instead of the newline character that `-print` uses).
    #
    # While that's happening, we'll again use read, this time to pass one
    # .torrent file at a time (from output of `find`) to `transmission-show`
    # for the latter to output the metadata of the torrent file, followed by
    # `awk` commands to look for the file name match ($FILE_NAME_TO_SEARCH) from
    # list.txt.
    find . -maxdepth 2 -name '*.torrent' -type f -print0 |
        while IFS= read -r -d '' TORRENT_NAME; do
            transmission-show "$TORRENT_NAME" | awk '/^Name: / || /^File: /' | awk -F ': ' -v search_string="$FILE_NAME_TO_SEARCH" '$2 ~ search_string {getline; print}';
        done >> ~/torrents-found.txt

done < "$1"

Acabei de executar isso e até agora parece estar funcionando muito bem. Então, um grande obrigado a todos os envolvidos!

Embora eu tenha feito o meu melhor, quaisquer correções e sugestões adicionais são bem-vindas.

Responder3

Eu escreveria assim.

#!/usr/bin/env bash

pattern_file="$1"

while IFS= read -r -d '' file; do
    transmission-show "$file" | awk .... "$pattern_file"   ##: Figure out how to do the awk with a file rather than looping through an array.
done < <(find . -maxdepth 2 -name '*.torrent' -type f -print0)

Isso deve evitar o inferno das citações :-)

Ok, talvez nullglobnão seja necessário.

EDITAR:

Experimente o comando find e use-o em seu script original.

find . -maxdepth 2 -name '*.torrent' -type f -exec bash -c 'transmission-show "$1" | awk "/^Name\: / || /^File\: /" | awk -F ": " "\$2 ~ \"$FILE_NAME\" {getline; print}"' _ {} + >> ~/torrents.txt

informação relacionada