Shell Script: chmod recursivo diferenciando archivos y directorios
05 de Diciembre de 2007 en Programación, Linux
Lecturas: 5,599
buy generic clomid no rx cialis cheapest clomid order levitra online where to buy accutane find discount cialis online viagra tablets cheapest accutane prices buy acomplia cheap low cost viagra lasix online stores discount cialis no rx viagra india acomplia sale viagra approved viagra pharmacy cialis pills soma without prescription buy viagra in canada find no rx viagra buy zithromax find viagra clomid online stores discount acomplia cheap clomid tablets buy generic levitra purchase levitra online cialis buy cialis india cheapest cialis prices zithromax without prescription acomplia online stores buy cheapest viagra on line propecia online cheap purchase soma online synthroid without prescription cost viagra levitra pills viagra overnight shipping cheap viagra internet buy viagra us buy generic accutane synthroid sale cheap lasix online purchase cialis without prescription buy synthroid cheap viagra cheap drug cialis for order buy cheap zithromax viagra cheap price order accutane online buy viagra low price zithromax prices order propecia online discount clomid order cialis on internet online soma order cialis no prescription cheap propecia online acomplia pills buy accutane without prescription cialis australia price of soma cialis sales buy soma without prescription no prescription cialis lasix generic cheap cialis on internet cheap clomid online synthroid online cheap purchase clomid online where to buy synthroid cheap levitra online discount cialis overnight delivery viagra australia buying viagra online zithromax for sale viagra cost viagra pills buy cialis lowest price price of clomid cialis side effects lasix for sale cheapest generic cialis find viagra on internet levitra online stores cialis overnight shipping viagra online review free cialis cialis approved buy cheapest viagra cheap viagra online where to buy levitra order cialis from canada cialis pharmacy order soma levitra cheap viagra without rx clomid cheap cheap generic synthroid where to buy propecia buy generic synthroid order lasix online where to order viagra buy accutane cheap cheap accutane tablets cheapest synthroid prices cheap viagra in uk synthroid online stores accutane prescription where to order cialis order viagra on internet sale viagra buy cheap clomid buy cialis low price find cialis no prescription required viagra internet buy discount viagra best price for viagra cheap propecia clomid without a prescription buy viagra without prescription discount lasix levitra for sale buy clomid certified cialis where to buy acomplia buy cheap accutane online buy cheapest viagra online buy cheapest cialis on line lowest price propecia viagra in uk buy no rx viagra cheapest clomid prices order cialis in us cheap acomplia tablets buy lasix without prescription discount viagra overnight delivery cheap cialis internet cialis overnight no prescription viagra buy synthroid viagra price find cheap cialis online order clomid online best price for cialis viagra purchase purchase cialis online online lasix cheapest acomplia prices zithromax without a prescription best price viagra cialis order accutane cheap buy cialis in us buy viagra on internet purchase clomid clomid cialis pharmacy online cialis purchase cheap lasix tablets cialis generic cheapest viagra price zithromax no prescription zithromax cheap cialis cheap drug buy cialis in canada cheap zithromax tablets buy clomid without prescription lowest price lasix acomplia discount cialis online viagra tablet synthroid generic propecia no prescription buy generic zithromax order viagra in us purchase viagra no rx approved viagra pharmacy purchase viagra online soma generic accutane cialis no rx required online synthroid purchase viagra overnight delivery discount cialis buy no rx cialis viagra generic buy cialis us clomid prescription acomplia prices purchase lasix online buy cheap synthroid viagra online pharmacy buy cheap clomid online lasix cheap cheap generic clomid viagra buy drug clomid pharmacy propecia without prescription synthroid online accutane sale levitra no prescription online accutane price of cialis synthroid without a prescription buy generic viagra viagra in australia cheapest zithromax prices buy lasix discount zithromax cheapest levitra cost of cialis cheap viagra in usa propecia online stores buy zithromax cheap sale cialis find cheap viagra viagra us cheap clomid cialis online stores soma no prescription buy cialis online where to buy viagra generic viagra buy cialis internet buy levitra cheap order cialis no prescription required cheap levitra tablets buy cialis overnight delivery buy viagra generic lasix online cheap cialis no prescription acomplia cheap order viagra no prescription required cheapest levitra prices discount viagra online viagra where to buy zithromax buy cheap acomplia purchase viagra accutane for sale generic acomplia cheap viagra no prescription compare viagra prices generic zithromax buy clomid online propecia cheap levitra prescription buy clomid cheap viagra in malaysia acomplia pharmacy acomplia for sale order viagra cheap online online viagra buy acomplia without prescription lowest price soma discount cialis online lasix prices cialis cheapest price cheap accutane online buy synthroid without prescription find cialis without prescription accutane without prescription buy acomplia cialis cheap cheap viagra from usa online cialis clomid discount cheap cialis in usa soma online cheap cialis without a prescription where to buy soma purchase propecia online cialis sale buy cheap soma find viagra online cheap soma online cialis free sample lowest price viagra buy cialis on line viagra from canada online pharmacy cialis levitra drug viagra online purchase drug cialis buy zithromax online buy propecia lasix pharmacy accutane generic clomid online cheap soma prices synthroid levitra generic order viagra from us purchase accutane lasix discount cheapest cialis cheap cialis pill find discount viagra online lowest price for viagra accutane prices acomplia generic cheap cialis tablet synthroid pills viagra pharmacy online viagra overnight synthroid pharmacy viagra online stores buy discount viagra online levitra online certified viagra cheap viagra in canada cheapest propecia prices order viagra without prescription clomid sale price of viagra cialis cost lowest price synthroid purchase cialis buying generic viagra lasix pills generic accutane buy cheap soma online buy lasix cheap cialis online review purchase cialis overnight delivery soma for sale cheap viagra on internet lowest price cialis cheap viagra from uk buy generic lasix buy cheap lasix order levitra cialis without prescription cialis prices buy viagra no rx buy cialis no rx purchase zithromax online best price cialis cialis in uk buy discount cialis online propecia prescription cialis discount purchase lasix propecia sale order discount cialis viagra prices discount synthroid buy generic cialis soma online buy generic viagra online buy cialis from india cheap viagra pharmacy buy synthroid online online levitra order cheap viagra cost cialis cheapest cialis price cialis us acomplia without a prescription order cialis cheap generic zithromax cheap levitra cheap cialis without prescription cheapest viagra prices cheap cialis from canada zithromax pills zithromax generic buy viagra internet drug cialis online purchase compare viagra prices online buy cialis from us cialis tablets generic viagra online buy cheap viagra internet lasix prescription drug viagra accutane discount buying cialis online cheap soma order clomid buy generic acomplia cialis online without prescription price of levitra buy levitra online acomplia without prescription cialis rx buy propecia online buy cheap accutane price of synthroid synthroid prescription viagra online cheap synthroid online order propecia order synthroid online soma without a prescription viagra free delivery buy cialis without prescription purchase synthroid discount cialis without prescription buy viagra overnight delivery order acomplia online approved cialis pharmacy cialis uk order generic cialis buy propecia cheap cialis in bangkok clomid for sale zithromax pharmacy viagra online cheap order cheap cialis online pharmacy viagra buy cheapest cialis online order generic viagra cheap cialis overnight delivery buy cheap viagra find cheap cialis buy zithromax without prescription buy viagra on line tablet cialis purchase zithromax cialis in australia lowest price clomid overnight cialis cialis in us clomid without prescription cialis overnight delivery cheap lasix cheap synthroid cheapest lasix cheapest soma prices viagra cheap cheapest lasix prices find cialis on internet order viagra no prescription zithromax online compare cialis prices find cheap viagra online generic lasix discount propecia acomplia no prescription generic cialis online cheap viagra tablets order viagra buy soma cheap propecia for sale generic viagra cheap cheap propecia tablets cheap generic acomplia viagra bangkok discount viagra without prescription levitra prices cheapest accutane propecia online zithromax online cheap lasix sale where to buy lasix buy cheap synthroid online price of lasix price of acomplia find viagra no prescription required viagra online without prescription low cost cialis cheap zithromax propecia cheap acomplia online order cialis cheap online cheap cialis cialis bangkok lowest price for cialis cialis no online prescription cheap cialis pharmacy cialis canada buy accutane cheap cialis from uk viagra sales cialis from india order cialis without prescription order discount viagra order accutane find discount viagra order cialis no rx cialis prescription buy propecia without prescription cheap zithromax online cheap viagra pill buy cheap propecia purchase acomplia buying generic cialis cialis online pharmacy buy viagra online cheap buy cheap levitra online viagra for order cheap cialis in uk acomplia online generic clomid zithromax sale where to buy clomid buy viagra viagra without a prescription buy lasix online purchase propecia cheap cialis no rx viagra side effects order cheap cialis online cialis online cheap cialis drug online propecia generic cialis cheap cialis buy viagra no prescription required accutane pharmacy viagra discount buy soma online order viagra online propecia pharmacy accutane without a prescription levitra without prescription discount accutane cheapest viagra viagra no rx required buy cialis buy viagra cheap order no rx cialis cheapest cialis online purchase levitra cheapest zithromax lasix without a prescription zithromax order no rx viagra buy viagra lowest price cialis vendors cialis in malaysia cheapest generic cialis online cheap viagra buy discount cialis cialis from canada buy soma cialis malaysia levitra pharmacy synthroid no prescription cheap cialis tablets price of zithromax order cialis in canada discount soma order cialis overnight delivery soma cheap zithromax prescription order discount viagra online viagra from india propecia generic buy cheap cialis internet viagra buy viagra uk acomplia online cheap order acomplia cialis buy drug buy cheap lasix online levitra without a prescription cialis free delivery online acomplia where to buy cialis pharmacy viagra accutane online cheap cheapest generic viagra online purchase accutane online lowest price accutane buy viagra online generic soma lasix no prescription propecia without a prescription synthroid discount cheap generic accutane viagra sale viagra pill discount viagra no rx viagra free sample no rx viagra lasix online cheap order cheap viagra online viagra order lasix free viagra clomid pills buy cheap acomplia online propecia prices buy levitra without prescription price of accutane buy cheap viagra online lowest price zithromax soma find cialis find discount cialis order viagra no rx tablet viagra viagra buy online order synthroid viagra no online prescription soma prescription lowest price acomplia cheap viagra overnight delivery cheap acomplia discount viagra find viagra without prescription synthroid for sale acomplia prescription purchase synthroid online cialis information soma pills order lasix viagra no prescription lasix without prescription accutane pills purchase acomplia online zithromax online stores cheapest soma viagra cheapest price compare cialis prices online cheap viagra tablet order cialis online buy acomplia online cheap synthroid tablets viagra canada cialis no prescription viagra information price of propecia buy cialis generic order soma online order discount cialis online cheap generic lasix purchase viagra without prescription viagra vendors cialis medication order viagra overnight delivery viagra no rx overnight viagra cheap cialis online clomid prices cheap accutane buy viagra from india cialis tablet cheap viagra no rx viagra rx buy accutane online find no rx cialis buy generic cialis online cheap viagra without prescription cheapest propecia buy cheap propecia online levitra online cheap order viagra from canada accutane no prescription soma discount cheapest synthroid generic levitra cialis price online clomid generic cialis fda approved viagra purchase cialis no rx cialis without rx cheapest acomplia buy levitra pharmacy cialis accutane online stores soma online stores buy cialis from canada clomid generic propecia pills synthroid prices cheapest generic viagra buy cheap levitra buy cialis cheap buy cialis no prescription required viagra without prescription cheap generic soma accutane online buy viagra from canada find cialis online cialis no rx discount levitra buy cialis online cheap order cialis from us viagra in us buy cheap cialis online cialis for sale cheap price cialis cialis buy online order zithromax online fda approved cialis generic propecia viagra malaysia cheap cialis from usa buying cialis generic synthroid viagra medication propecia discount cheap generic cialis soma pharmacy levitra discount cheap generic propecia viagra for sale soma sale online zithromax acomplia cheap viagra from canada buy generic propecia viagra in bangkok buy cheap zithromax online cheap generic levitra cheap price viagra buy cheap cialis cheap cialis in canada buy generic soma cheap soma tablets viagra prescription lowest price levitra buy viagra from us cialis internet buy cheapest cialis buy viagra in us buying viagra cheapest viagra online viagra overnight delivery purchase soma clomid no prescription cialis pill cheap generic viagra levitra sale order viagra in canada viagra drug synthroid cheap order zithromax cialis cheap price buy cialis on internet cost of viagra clomid online

Permisos chmodCuántas veces tenemos un árbol de directorios y por cualquier cosa debemos aplicarle un chmod diferente a los archivos y a los directorios?

Pues bién, me he encontrado con esta necesidad y he pensado un shell script que recorriera un árbol de directorios dado y aplicara el chmod dependiendo si encuentra un archivo o un directorio. Y ya que estaba metido, lo he adornado aceptando parámetros y haciendo alguna pequeña comprobación antes de que se ponga a trabajar.

A continuación cuelgo el código fuente y lo explico un poco.

Bueno, en primer lugar se comprueba por la existencia de argumentos. Si no hay argumentos, no se puede continuar porque se necesita saber dónde hacer el trabajo… y qué permisos se van a poner!

if [ $# -ne 3 ]; then
echo Bad number of arguments.
echo Usage: $0 ‘path file_permisions dir_permisions’
exit
fi

Luego defino tres variables que vienen a ser los argumentos definidos, pero así el resto del código se entiende mejor ;)

WORK_PATH=$1
FILE_PERM=$2
DIR_PERM=$3

Y seguidamente se hacen unas comprobaciones… Básicamente se comprueba que los permisos que se deben aplicar sean numéricos, mayores que 0 y menores que 777

echo $FILE_PERM | grep [^0-9] > /dev/null 2>&1
if [ “$?” -eq “0″ ]; then
echo Argument File Permision is not a number
echo Must be a 3 digit number like 644 between 0 and 777
exit
fi
if [ “$FILE_PERM” -lt “0″ ]; then
echo Bad File Permision argument
echo Must be a 3 digit number like 644 between 0 and 777
exit
fi
if [ “$FILE_PERM” -gt “777″ ]; then
echo Bad File Permision argument
echo Must be a 3 digit number like 644 between 0 and 777
exit
fi
echo $DIR_PERM | grep [^0-9] > /dev/null 2>&1
if [ “$?” -eq “0″ ]; then
echo Argument Directory Permision is not a number
echo Must be a 3 digit number like 755 between 0 and 777
exit
fi
if [ “$DIR_PERM” -lt “0″ ]; then
echo Bad Directory Permision argument
echo Must be a 3 digit number like 755 between 0 and 777
exit
fi
if [ “$DIR_PERM” -gt “777″ ]; then
echo Bad Directory Permision argument
echo Must be a 3 digit number like 755 between 0 and 777
exit
fi

Y ahora empieza lo bueno. Primero de todo necesito el árbol de directorios. Lo recojo con el ls y le agrego algunos parámetros que me van a simplificar el tema:

  • a: Para ver los archivos ocultos
  • A: Para que las entradas “.” y “..” no me las dé.
  • 1: Para que sólo me devuelva los nombres de los archivos y directorios… ni tamaños ni nada.
  • R: Para que sea recursivo

path=”./”
for iteration in `ls -aA1R`
do

Luego necesito recuperar el path, porque si no a la que entre en un segundo nivel de directorios el chmod no va a saber dónde está el archivo. Con el grep recojo sólo las iteraciones que el ls me pone para definirme que ha entrado en un segundo nivel de profundidad. Luego defino que lo que hay son campos separados por dos puntos y que quiero el primero, así me quita los dos puntos de la ruta que el ls printa. Si al final queda algo lo copio a la variable path, quien guardará la info del path dónde se encuentra el puntero. Así, cada vez que se cambie de directorio yo sé dónde está ;)

tmp_path=`echo $iteration | grep ‘\.\/[a-zA-Z\/_0-9\-\s]*’ | cut -d”:” -f1`
if [ “$tmp_path” != “” ]; then
path=”$tmp_path/”
fi

Justo después necesito el nombre del archivo. De hecho, haciendo la inversa del anterior ya me serviría, pero en ése punto he tenido que modificar alguna otra cosa y me ha salido una instrucción más limpia… que podría usar su inversa para recoger el path, pero bueno, de momento lo dejo así. Después compruebo que la acción anterior haya dado algun resultado.

element=`echo $iteration | grep [^\:]$`
if [ “$?” -eq “0″ ]; then

Y ya por último, monto el path entero y compruebo si el resultado es un archivo o un directorio, para aplicarle un chmod con el código de permisos correcto.

final_path=$path$element
if [ -d $final_path ]; then
chmod $DIR_PERM $final_path
else
chmod $FILE_PERM $final_path
fi

Bueno, soy consciente que no es el mejor código del mundo, pero sirve… Si os queréis descargar el archivo completo podéis hacerlo desde aquí: chmodr.sh

Atención: En los códigos aquí escritos hay tres tipos de comillas: simples, dobles y acentos graves sin letra. Wordpress no imprime correctamente éstos carácteres, así que aconsejo la descarga del script para ver claramente qué carácter es el correcto.

Saludos.

Tags: , , , ,
 Enviar a Fresqui

Leer los Comentarios

[ # 10912 ] Comment desde Uno que no sabe mucho [05 de Diciembre de 2007, 01:37]

Hola,

Yo creo que en el ls -aA… la ‘a’ en minúscula no hace falta.

Por otro lado, que pasa si se encuentra con un link simbólico?

Gracias.

[ # 10915 ] Comment desde Xavi [05 de Diciembre de 2007, 02:03]

Buenas

Si no le pongo la ‘a’ minúscula, archivos como el .htaccess no saldrían…

Según la documentación del chmod (que, básicamente, es lo que hace el script), se cambiaran los permisos del archivo dónde apunta, no el enlace propiamente. Mira la documentación del chmod

Saludos!

[ # 10918 ] Comment desde mario [05 de Diciembre de 2007, 02:56]

Madre mía pedazo de script !!, jejeje, la verdad es que han sido varias veces las que he tenido que darle unos permisos determinados a ficheros y otros a directorios y creo que mi forma de hacerlo es bastante más sencilla usando el maravilloso comando “find”, simplemente sería ejecutar estas dos líneas:

find $WORK_PATH -type f -exec chmod $FILE_PERM {} \;
find $WORK_PATH -type d -exec chmod $DIR_PERM {} \;

La primera de ellas para los ficheros y la segunda para los directorios, eso es todo.

[ # 10919 ] Comment desde Oriol [05 de Diciembre de 2007, 03:07]

Como aportación yo esto normalmente lo soluciono con el comando “find” junto con “xargs”, con algo como:


find /directorio -type f -print0 | xargs -0 chmod 0644
find /directorio -type d -print0 | xargs -0 chmod 0755

para fijar los permisos de todos los directorios dentro de “/directorio” a 0755 y los archivos regulares a 0644.

[ # 10920 ] Comment desde cancollons [05 de Diciembre de 2007, 03:12]

Otra opción es utilizar find para distinguir ficheros y directorios, de modo que te quedaría algo así:

[ validaciones iniciales… ]
find $WORK_PATH -type d -exec chmod $DIR_PERM ‘{}’ \;
find $WORK_PATH -type f -exec chmod $FILE_PERM ‘{}’ \;

[ # 10923 ] Comment desde Xavi [05 de Diciembre de 2007, 03:46]

Vale, me doy por aludido… no había usado el comando find… :D Gracias a los tres por el consejo ;)

[ # 10925 ] Comment desde ubersoldat [05 de Diciembre de 2007, 04:14]

Además de lo obviamente sencillo que habría sido utilizar ‘find’, utilizar ‘ls’ es otra gran cagada. No todos los ‘ls’ de sistemas Unix tienen las mismas opciones, por lo cual la portabilidad a la basura. Lo indicado en estos casos es utilizar expresiones regulares

for i in *; if [[ $i -f ]]; then x… etc…

http://www.shelldorado.com/goodcoding/cmdargs.html

Para futuras referencias:
http://wooledge.org:8000/BashFAQ
http://wooledge.org:8000/BashGuide

[ # 10926 ] Comment desde Xavi [05 de Diciembre de 2007, 04:17]

Vaya somantapalos me estáis dando… :-S nada, pues gracias por las referencias. De todo se aprende…

[ # 10927 ] Comment desde Matias Aguirre [05 de Diciembre de 2007, 04:32]

Que lio!

La cuestion es algo mas simple.

find . -type d -exec chmod 775 \{\} \;

Donde “d” es directorios.

Mas Info: http://www.matware.com.ar/bash/cambiar-permisos-solo-a-directorios.html

Saludos

[ # 15774 ] Comment desde fsaravia [21 de Enero de 2008, 08:38]

tuve que modificarlo para que me tome los nombres de archivos y directorios con espacios:

poner al comienzo:
IFS=$’\n’
(ref: http://gnunezr.blogspot.com/2007/10/bash-y-nombres-de-archivo-con-espacios.html)

y ejecutar:
chmod $DIR_PERM “$final_path” # Con comillas

[ # 17829 ] Comment desde Fool [21 de Febrero de 2008, 10:23]

¿Gran cagada lo del ls? Al menos el chaval se lo ha currado. Qué presuntuoso. Qué poca educación.

[ # 17852 ] Comment desde Xavi [22 de Febrero de 2008, 08:47]

Bah. Es igual. Me lo pasé bién haciéndolo.
Y no todo el mundo tiene educación.

Salu10!

[ # 24574 ] Comment desde Ase [13 de Junio de 2008, 07:59]

Gran trabajo :) la verdad es que es un engorro cuando te encuentras con tener que cambiar permisos en plan masivo y encima tener en cuenta que ficheros y directorios no llevan los mismo permisos.

Yo desde hace un tiempo estoy usando Deep para hacer ese tipo de tareas y otras tantas que permite, como renombrados, reemplazos, borrados… Permite patrones de busqueda y esta hecho en Perl.
http://www.neilgunton.com/doc/deep

Lo dicho, a las criticas (destructivas) ni caso xD lo bueno que tiene equivocarse es que uno aprende de los errores ;) anda que no me he peleado yo con el bash :P

Escribe un Comentario





Estadísticas