logo

Bash Scripting: cómo comprobar si existe un archivo

En este artículo, escribiremos un script bash para comprobar si los archivos existen o no.

Sintaxis:

  • prueba [expresión]
  • [ expresión ]
  • [[ expresión ]]

Aquí, en expresión, escribimos parámetro y Nombre del archivo . Veamos algunos parámetros que se pueden utilizar en la expresión: –

  • F: Devuelve True si el archivo existe como un archivo común (normal).
  • -d: devuelve Verdadero si el directorio existe. -e: Devuelve Verdadero si existe algún tipo de archivo. -c: Devuelve Verdadero si el archivo de caracteres existe. -r: Devuelve Verdadero si existe un archivo legible.
  • En : Devuelve Verdadero si existe un archivo grabable .
  • -x: Devuelve Verdadero si existe un archivo ejecutable. -p: Devuelve Verdadero si el archivo existe como una tubería. -S: Devuelve Verdadero si el archivo existe como un socket. -s: devuelve Verdadero si existe un archivo y el tamaño del archivo no es cero. -L: Devuelve True si el archivo del enlace simbólico existe . -g: Devuelve Verdadero si el archivo existe y se establece el indicador de ID de grupo establecido. -G: I t devuelve True si el archivo existe y contiene la misma identificación de grupo que está en proceso. -k: Devuelve Verdadero si el archivo existe y el indicador de bit fijo está configurado.

Ahora, hay algunos parámetros más para comparar entre los dos archivos.



    -ef: Devuelve True si ambos archivos existen e indican el mismo archivo.

Ejemplo :

FirstFile -ef SecondFile>
    -nt: devuelve True si FirstFile es más nuevo que Secondfile.

Ejemplo :

que es un monitor
FirstFile -nt FileOld>
    -ot: Devuelve Verdadero si el PrimerArchivo es anterior al SegundoArchivo.

Ejemplo:

FirstFile -ot SecondFile>

Tomemos algunos ejemplos basados ​​en la sintaxis:

    [expresión]: Primero, cree un archivo llamado FirstFile.sh y escriba el siguiente script en él
#!/bin/bash # using [ expression ] syntax and in place # of File.txt you can write your file name if [ -f 'File.txt' ]; then # if file exist the it will be printed echo 'File is exist' else # is it is not exist then it will be printed echo 'File is not exist' fi>

Ahora guarde y ejecute el archivo usando el siguiente comando

$ chmod +x ./FirstFile.sh $ ./FirstFile.sh>

Producción :

Producción

Nota: Como el File.txt está presente en el sistema. Entonces, imprimió El archivo existe.

    prueba [expresión]: Ahora, modifique el script anterior en FirstFile.sh de la siguiente manera
#!/bin/bash # using test expression syntax and in place # of File2.txt you can write your file name if test -f 'File2.txt' ; then # if file exist the it will be printed echo 'File is exist' else # is it is not exist then it will be printed echo 'File is not exist' fi>

Ahora, guarde y ejecute nuevamente el archivo usando el siguiente comando

búsqueda binaria en java
$ chmod +x ./FirstFile.sh $ ./FirstFile.sh>

Producción :

Producción

Nota: Como File2.txt no está presente en el sistema. Entonces, imprimió que el archivo no existe.

    [[ expresión ]]: Modifique nuevamente el script anterior en FirstFile.sh de la siguiente manera
#!/bin/bash # using [[ expression ]] syntax and in place # of File3.txt you can write your file name if test -f 'File3.txt' ; then # if file exist the it will be printed echo 'File is exist' else # is it is not exist then it will be printed echo 'File is not exist' fi>

Ahora, guarde y ejecute nuevamente el archivo usando el siguiente comando

 $ chmod +x ./FirstFile.sh $ ./FirstFile.sh>

Producción :

Producción

Nota: Como File3.txt está presente en el sistema. Entonces, imprimió que el archivo existe.

Veamos un ejemplo basado en parámetros:

    Usando el parámetro -d: cree un archivo llamado FirstDir.sh y escribe el siguiente script en él
!/bin/bash if [[ -d 'GFG_dir' ]] ; # Here GFG_dir is directory and in place of GFG_dir you can write your Directory name then echo 'Directory is exist' # If GFG_dir exist then it will be printed else echo 'Directory is not exist' # If GFG_dir is not exist then it will be printed fi>

Ahora guarde y ejecute el archivo usando el siguiente comando

variables globales js
$ chmod +x ./FirstDir.sh $ ./FirstDir.sh>

Producción :

Producción

Nota: Como GFG_dir está presente en el sistema. Entonces, imprimió el directorio existe.

Del mismo modo, puedes utilizar -F , -Es , -En , -r , -C ,etc. (según sus usos) en lugar de -d para comprobar la existencia de diferentes tipos de archivos.

Veamos un ejemplo basado en una comparación de dos archivos:

  • Usando -Nuevo Testamento parámetro

Cree un nombre de archivo Comparison_File.sh y escriba el siguiente script

#!/bin/bash # New_file.txt and Old_File.txt are names of two files. if [[ 'New_File.txt' -nt 'Old_File.txt' ]] ; then # This will be printed if Condition is true echo 'New_File.txt is newer than Old_File.txt' else # This will be printed if Condition is False echo 'New_File.txt is not newer than Old_File.txt' fi>

Ahora guarde y ejecute el archivo usando el siguiente comando

 $  chmod +x ./Comparison_File.sh $ ./Comparison_File.sh>

Producción :

Producción

Nota: Como ambos archivos están presentes en el sistema y New_File.txt es más nuevo que Old_File.txt

estructuras de datos en java

Veamos el ejemplo Comprobar si el archivo no existe:

Cree un archivo llamado Check_Exist.sh y escribe el siguiente script en él

#!/bin/bash # using ! before -f parameter to check if # file does not exist if [[ ! -f 'GFG.txt' ]] ; then # This will printed if condition is True echo 'File is not exist' else # This will be printed if condition is False echo 'File is exist' fi>

Ahora guarde y ejecute el archivo usando el siguiente comando

 $ chmod +x ./Check_Exist.sh $  ./Check_Exist.sh>

Producción :

Producción

Nota: GFG.txt no está presente en el sistema. Entonces imprimirá. El archivo no existe.

Veamos un ejemplo sin utilizar la condición If-else:

Cree un archivo llamado Geeks_File.sh y escriba el siguiente script en él

#!/bin/bash # If File exist then first statement will be # printed and if it is not exist then 2nd # statement will be printed. [ -f 'GFG_File.txt' ] && echo 'File is exist' || echo 'File is not exist'>

Ahora guarde y ejecute el archivo usando el siguiente comando

 $ chmod +x ./Geeks_File.sh $ ./Geeks_File.sh>

Producción :

Producción

Nota: Como GFG_File.txt está presente en el sistema. Entonces, imprimió que el archivo existe.