Sair do bash quando o find chegar a uma pasta com permissão negada

3

Estou tentando escrever meu segundo script Bash. Onde eu atravesso pastas de forma recursiva e faço uma lista de arquivos e pastas.

De certa forma funciona, mas se "find" chegar a um diretório em que tenha permissão negada, apenas o script continua. Ignorando o diretório sem contar os arquivos nele nem informando que o diretório está com permissão negada. (diferente de um comando de terminal inútil que não posso usar, pois os scripts são executados por meio de ações personalizadas do gerenciador de arquivos)

Eu gostaria que quando "encontrar" encontrasse uma pasta de permissão negada para interromper o processo de pesquisa e relatar para mim qual pasta tinha permissão negada. Então eu sei o que está pulando e por quê.

Eu tentei pesquisar no google por alguns dias e tentei muitas tentativas diferentes, mas não consegui resolver isso sozinho.

Metade do meu código parece com isso

#!/bin/bash

allfolders=("$@")
nfolders="0"

Nfilesinfolders="0"
filesinfolder="0"

results=""
noteadded="0"

for directory in "${allfolders[@]}"; do

    echo "This is where I try and insert the code examples below.
    echo "and want it to exit with a zenity error"

    nfolders=$(( nfolders + 1 ))
    echo "$nfolders"

if [[ $nfolders -ge 11 ]]
    then
      if [[ $noteadded -ge 0 ]]
        then
          results+="\n"
          results+="Not adding any more folders to the list. Look at the top for total number of files"
          noteadded=1
      fi
 else
     results+="$directory\n"
 fi

 echo "This below attempt only worked on the top folder not folders in it"

 if [[ -r "$directory" ]] && [[ -w "$directory" ]]
     then
         filesinfolder=$(find "$directory" -depth -type f -printf '.' | wc -c)
         Nfilesinfolders=$(( Nfilesinfolders + filesinfolder ))
     else
         zenity --error --title="Error occured check message" --text="The directory\n $directory\n is not readable or write-able to you $USER\n please run as root"
         exit $?
    fi
done

Aqui estão algumas das minhas tentativas fracassadas

find "$directory" -depth -type d -print0 | while IFS= read -r -d $'
shredout=$(find "$directory" -depth -type d -print0 2>&1 | grep "Permission denied" && echo "found Permission Denied" && checkfolderperm="1" )

if [[ $checkfolderperm -eq 1 ]] 
    then
        zenity --error --title="Error occurred check message" --text="The directory\n $directory\n is not readable or write-able to you $USER\n please run as root"
        exit $?
fi
' currentdir do echo "Checking "$currentdir" in directory "$directory"" if [[ ! -r "$currentdir" ]] && [[ ! -w "$currentdir" ]] then zenity --error --title="Error occurred check message" --text="The directory\n $currentdir\n is not readable or write-able to you $USER\n please run as root" exit $? fi done

O código acima parece estar sendo ignorado e continua no script.

O próximo ficou assim. Eu poderia fazer com que ele informasse um erro, mas não me dissesse qual pasta deu errado.

while IFS= read -r -d $'
if finderrors=$(! find "$directory" -depth -type d 2>&1 1>/dev/null)
    then 
        zenity --error --title="Error occurred check message" --text="$finderrors"
        exit $?
fi
' currentdir; do echo "going through file = $currentdir in folder $directory" if [[ ! -r "$currentdir" ]] && [[ ! -w "$currentdir" ]] then zenity --error --title="Error occured check message" --text="The directory\n $currentdir\n is not readable or write-able to you $USER\n please run as root" exit $? fi done < <(find "$directory" -depth -type d -print0)

Mas o acima também parece estar sendo ignorado.

o último é mais parecido com a minha primeira tentativa.

#!/bin/bash

allfolders=("$@")
nfolders="0"

Nfilesinfolders="0"
filesinfolder="0"

results=""
noteadded="0"

for directory in "${allfolders[@]}"; do

    echo "This is where I try and insert the code examples below.
    echo "and want it to exit with a zenity error"

    nfolders=$(( nfolders + 1 ))
    echo "$nfolders"

if [[ $nfolders -ge 11 ]]
    then
      if [[ $noteadded -ge 0 ]]
        then
          results+="\n"
          results+="Not adding any more folders to the list. Look at the top for total number of files"
          noteadded=1
      fi
 else
     results+="$directory\n"
 fi

 echo "This below attempt only worked on the top folder not folders in it"

 if [[ -r "$directory" ]] && [[ -w "$directory" ]]
     then
         filesinfolder=$(find "$directory" -depth -type f -printf '.' | wc -c)
         Nfilesinfolders=$(( Nfilesinfolders + filesinfolder ))
     else
         zenity --error --title="Error occured check message" --text="The directory\n $directory\n is not readable or write-able to you $USER\n please run as root"
         exit $?
    fi
done

mas também é ignorado.

Existe alguma maneira de eu passar por pastas com o find. Em seguida, pare e informe se um diretório é permissão negada.

Eu me deparei com "armadilhas" bash e bash "funções", mas não consigo descobrir se elas são a minha solução ou como usá-las.

Esta é minha primeira tentativa de escrever uma pergunta bash, então espero ter escrito o código corretamente e não cometido muitos erros.

Este é o código resultante após a ajuda do "meuh". Ele para o script e informa exatamente para qual pasta / pasta ele não tem permissão. Espero que possa ajudar outras pessoas como eu.

find "$directory" -depth -type d -print0 | while IFS= read -r -d $'
shredout=$(find "$directory" -depth -type d -print0 2>&1 | grep "Permission denied" && echo "found Permission Denied" && checkfolderperm="1" )

if [[ $checkfolderperm -eq 1 ]] 
    then
        zenity --error --title="Error occurred check message" --text="The directory\n $directory\n is not readable or write-able to you $USER\n please run as root"
        exit $?
fi
' currentdir do echo "Checking "$currentdir" in directory "$directory"" if [[ ! -r "$currentdir" ]] && [[ ! -w "$currentdir" ]] then zenity --error --title="Error occurred check message" --text="The directory\n $currentdir\n is not readable or write-able to you $USER\n please run as root" exit $? fi done
    
por Darkyere 26.08.2015 / 11:59

1 resposta

8

find definirá seu código de retorno como diferente de zero se ele viu um erro. Então você pode fazer:

if ! find ... 
then    echo had an error >&2
fi |
while ...

(não tenho certeza do que você quer fazer com a saída de localização).

Para coletar todas as mensagens de erro de find no stderr (descritor de arquivo 2), você pode redirecionar 2 para um arquivo. Por exemplo:

if ! find ... 2>/tmp/errors
then     zenity --error --text "$(</tmp/errors)"
fi |
while ...
    
por 26.08.2015 / 12:06