Check if a file or folder exists or not (and more) with IF loop

I have not put anything of Bash, and it is that while I was entering the wonderful world of Python I have forgotten a little about this other friend who helped me so much 🙂

Here I put something to Bash enthusiasts, as the title says ... I will show you how to check whether or not a file or folder exists in the system, just using: if

We are going to create a .sh file and give it execution permissions, for this, just put the following command in a terminal:

touch test.sh && chmod + x test.sh

What this did is create the file (touch test.sh) and also give you execution permissions (chmod + x test.sh)

Then let's write the following in it:

if [ -d /opt/ ];
then
echo "Sí, sí existe."
else
echo "No, no existe"
fi

What does this?

Simple 😀

In the first line - » if [-d / opt /];

Here we ask, does the / opt / directory exist? Yes directory / folder, because the -d means directory or folder.
Then in case it exists we will print in the terminal «Yes, it does exist.»(This is line 2 and 3)
Otherwise and / opt / does NOT exist, then we will print «No it doesn't exist»(Lines 4 and 5)
Then in the last line (number 6) we close the if and that's it.

Related article:
Establish network connection between the PC and Virtualbox virtual machines

Do the test, it will show you that / opt / does exist.

If you want me to show you the other text (the one that does not exist) change / opt / for any other folder that does not exist in your system, for example: / asd /

As you can see, -d helps us to know if the directory exists, well now if we change -d to -f it is to check the existence of files (-d = directory, -f = file / file)

For example:

if [ -f /etc/hosts ];
then
echo "Sí, sí existe."
else
echo "No, no existe"
fi

Here is the list of options:

-d - »Check if a certain directory exists

-f - »Check if a certain file exists

-w - »Check if a certain file has write permissions

-x - »Check if a certain file has execution permissions.

And well there is not much more to add 🙂

I know this will be very useful and interesting for those who like to program in Bash 😉

regards


The content of the article adheres to our principles of editorial ethics. To report an error click here!.

42 comments, leave yours

Leave a Comment

Your email address will not be published. Required fields are marked with *

*

*

  1. Responsible for the data: Miguel Ángel Gatón
  2. Purpose of the data: Control SPAM, comment management.
  3. Legitimation: Your consent
  4. Communication of the data: The data will not be communicated to third parties except by legal obligation.
  5. Data storage: Database hosted by Occentus Networks (EU)
  6. Rights: At any time you can limit, recover and delete your information.

  1.   Hugo said

    Another way to do it without if… then..else:

    test -f /etc/hosts && elcomando

    Or also

    test ! -f /etc/hosts && echo "no se encontró el archivo"

    Etc.

    1.    KZKG ^ Gaara said

      Right 😀
      … O_O… Are you Hugo, Hugo from Cuba? … Using Windows8, WTF !!!

      1.    Hugo said

        Well yes, I am getting familiar with this OS and if I have to be frank, the only thing that I have found useful is the copy manager, otherwise I personally find it a pain, especially its hybrid interface and the metro applications. I like it less than the Vista and the 7 (albeit a bit more efficient than these), which I didn't like either. The only thing I'm using it for is playing NFS13 and Skyrim, but this OS takes so much space that I had to delete my Linux partition [snif].

        However, for your peace of mind, I will tell you that the day before yesterday I downloaded the Arch ISO for January and I plan to give it a little test in its x86-64 version, as soon as I get the repo (will you have it?). Now that as I saw it uses signed packages by default, it gives me more confidence to dive in.

        And my father also told me that he would send me a Sony Xperia, which I want to take advantage of to learn some programming for Android, which was a pending wish. So calm down, I have not yet gone to the dark side of the force, buahahahaha 😉

  2.   patz said

    man test

    1.    msx said

      Sure.

  3.   RAW-Basic said

    Wenas! ..

    We could make the same one .. ..but the directory is passed as a parameter ..

    if [ -d $1 ];
    then
    echo "Sí, sí existe."
    else
    echo "No, no existe"
    fi

    And we call it as:

    ./test.sh / opt /

    Greeting..

  4.   own said

    IF is not a cycle xD

  5.   Gregory Swords said

    It suits me like a glove for a script I'm doing. Is it valid to use wildcards? For example, to find out if there are any .mp4s then run something on them.

    if [-f * .mp4];
    ...

    1.    RAW-Basic said

      Yes, it is totally valid ..

      Even through parameters .. "* .mp4"

      1.    RAW-Basic said

        Eg

        if [ -f $1 ];
        then
        rm -r $1
        else
        ls
        fi

        If you call it: ./test.sh * .mp4

        If it finds .mp4 files, it deletes them ... ... but it does not list the files in that directory ...

        1.    Gregory Swords said

          Thanks for the feedback and tips! 🙂

        2.    Joaquin said

          You missed the f xD

          rm -rf $ 1

          This is more exciting!

        3.    b1tblu3 said

          Wonderful !!!, Every day I fall more in love with Linux, Windows has been relegated to some dark corner of my Hard Drive, which is about to be erased to give way to the light of Linux.

          1.    RAW-Basic said

            Excellent! .. ..then take the next step .. and get it out ..

            6 months ago approx. I have only GNU / Linux on all my machines and I don't need more .. ..not W $ .. or Wine .. ..and I'm more than happy like that .. 😉

            And I am infecting my surroundings .. since everyone sees me with my Arch, fast, efficient and happy .. ..and they ask me to install Linux .. ..yeah! .. 😀

        4.    Inukaze said

          You can also check them for various extensions, you can use something like

          #! / Bin / bash
          Directory = $ HOME / Downloads

          if [$ Directory]; then
          echo "Here is a List of File Types:"
          echo "mp1, mp2, mp3, mp4, wav, flac, flaad, aud, midi"
          ls {* .mp?, *. wav, *. fla, *. aud * .midi}
          fi

          using {} allows you to specify multiple extensions in this case, using "?" , is a wildcard, which allows you to take "Any Character".

          I hope you learn

        5.    pedro said

          I recommend the command find [directory] [search_pattern] –exec [command] {} \

      2.    Carlos said

        It doesn't work, I put these files in the directory:
        AB20160420.TXT
        AB20160421.TXT
        AB20160422.TXT
        AB20160423.TXT
        AB20160424.TXT
        AB20160425.TXT
        search.sh

        #! / Bin / bash
        PATH = / tmp / TEST
        cd $ ROUTE
        ls -la | awk '{print »« $ 9}'
        if [[-f AB.TXT]]; then
        echo »Enter the IF if there is any AB
        .TXT »
        fi
        if [-f AB20160422.TXT]; then
        echo "input for a specific AB file"
        fi

        when I put [-f AB.TXT] gives error
        when I put [[-f AB
        .TXT]] does not give an error but cannot find the file
        it only works when I put a specific file, for example:
        if [-f AB20160422.TXT]; then

        I can't get it to work with wildcards * or?

        1.    pedro said

          #! / usr / bin / env bash
          #.encoding = utf-8.

          CONSTANTS

          EXIT_OK = 0
          EXIT_BAD = 66

          BOLD = »\ 033 [1m»
          NC = »\ 033 [0m»
          RED = »\ 033 [31m»

          if [! "$ 1"];
          then
          echo "missing a parameter"
          exit $ EXIT_BAD
          fi

          cd "$ 1"

          files = »ls -h1 $ 1»

          for file in $ ($ files); do
          echo -e "you can do anything with $ BOLD $ file $ nc here"
          done

          exit $ EXIT_OK

  6.   msx said

    @KZ, tell more about this: «and that is because I am entering the wonderful world of Python»!

    1.    KZKG ^ Gaara said

      HAHAHAHA nah ... little by little 🙂
      I'm still just a newbie to Python, I hardly have time to dedicate hours and hours to it, so I am slow yes, slow but sure in my learning 😀

  7.   audoban said

    Thank you very much 😀 just yesterday I was thinking how to do this.

  8.   ReichSk said

    this with ncurses is great 🙂

  9.   Jazeco said

    in 1 word… EXCELLENT!
    For a long time I was perfecting a script to make downloads from the Internet, but I had the problem that it downloaded the files that it requested 1 and again without being able to verify the existence 1ro.
    Very good tuto.

  10.   zulan said

    Tremendous contribution, here from Chile is appreciated.
    Every day more LINUX pleasantly surprises me,
    Long live Free Software MIERDAAAA.

  11.   David said

    serve for
    check if a file is from a directory

  12.   Grovher said

    If I want to check the existence of any file in a path «/ tmp / receivers», execute any command, how would it be?

    I will be very grateful

    regards

  13.   Juan said

    Dear, and to determine by IF if the file is fully populated ???. I ask this because when you are filling the file for a transmission, it can take it even with half the data.

    Greetings and thanks for your response.

  14.   Inukaze said

    Well I think you should also add an example, such as "Check that there is no" a "file" or "directory" as for example

    to check that it does NOT exist, for example use a variable->

    A Directory

    #! / Bin / bash
    Directory = »$ HOME / Test Directory»
    File = »$ HOME / Test File»

    if [! -d "$ Directory"]; then
    echo "There is no $ Directory"
    echo "Creating ->" $ Directory "
    mkdir "$ Directory"
    else
    echo "Directory" $ Directory "already exists
    fi

    if [! -d "$ File"]; then
    echo "File $ does not exist"
    echo "Creating ->" $ File "
    touch "$ File"
    else
    echo "File" $ File "already exists
    fi

    1.    Katekyo said

      when you do the mkdir check later if the terminal could create it because it can break the balls if it is a folder as root or system hhah

  15.   Julius vinachi said

    Greetings KZKG ^ Gaara a query as I would do to use curl. I would like to know how I do from the console to ping a url to see if it is available for example http://portal.com/directorio/archivo1.php Where file1 will be storing the visit IPs, it is for monitoring a team that I need to make that pin every half hour so that I am aware of the public IP since it changes from time to time and I cannot connect by ssh .

    Greetings thank you in advance God bless you.

    1.    KZKG ^ Gaara said

      Hello there,

      First, you have to say that the IP variable (for example) is the content of that file, for this you have to:
      1. Download the file
      2. See its content and get the IP from there
      3. That IP is the variable

      For example:
      Here we download the file - »wget http://portal.com/directorio/archivo1.php -o file.html
      Then we assign a variable its content: - »: $ {IP: =` cat file.html`}
      .. assuming that the content of that file only has the IP, if not, you would have to work with grep, awk or head.

      Once you already have the IP as a variable, the rest is the simplest thing in the world 🙂

      If you want write me to the email (kzkggaara [at] desdelinux [dot] net) that I will gladly help you

      1.    Julius vinachi said

        Thank you very much kzkggaara very grateful.

  16.   Natalia said

    Hi, I don't understand much about computing and I don't know if this post is related to the problem I have.

    I comment in case you read me, even though the post is from a year ago:
    It turns out that I created a folder on my desktop to store some videos. Well, I deleted those videos because I no longer needed them and now this folder tells me that it does not exist (even though it is visible on my desktop).

    - That is the first problem I have:
    I can't delete the folder.

    - Second problem and I think more important:
    In an attempt to delete the folder, I put a PHOTOS folder. Now when I open the folder that "does not exist" it is empty and the PHOTOS are not there.

    How can I recover the photos? I have given the option inside the "Show hidden documents" folder but the PHOTOS folder does not appear.

    I hope you can know how it is solved.
    Thank you.

    1.    holds said

      There are two users who are the main ones: root and your_user (natalia for example). They both have personal folders. your_user in / home and root in / (root directory). By right clicking on the folder see who it belongs to. If it is root with your file manager using sudo or gksu or kdesu depending on the environment you use go to the root directory -> root -> Desktop and you will probably find the photos and you can delete the folder. Some distros when you are not the owner of the file or directory and you do not have access permissions tell you directory / file does not exist. If you are the owner and you are not root, do the same with the file manager with sudo, etc and go to the root directory -> / home -> personal_folder -> Desktop and see if the photos are there and if you can delete the folder.
      If this does not work, you will have to see other options from the terminal (console).

  17.   Pedro Manuel Aguayo Munoz said

    Hi, how are you? I am doing a job in bash and I would like to know how to verify if there is a directory entered from the keyboard, for example

    #! / Bin / bash
    read route
    #Enter ~ / Desktop
    #Then I try to navigate that directory
    cd $ path
    # I get the following bash message: cd: ~ / Desktop: The file or directory does not exist

    My question is, what can I do so that I enter it from the keyboard and take it as a directory path?

  18.   Miguel said

    And how can I know if a group exists,

  19.   heidi said

    good I have a problem in my canaima when I press the button cunaguaro it says that there is no file or directory as it would do to solve that problem and the rest does not open cunaguaro please thank you.

  20.   Carlos said

    How do you do the if in BASH if the filename has spaces?
    For example:
    April data.xlsx

    To ask if the file exists

    1.    Manuel Alcocer Jimenez said

      Carlos, like this:

      if [["$ variable" == Data \ month \ of \ April.xlsx]]; then echo 'match'; fi

      You can too:
      if [["$ variable" == 'Data for the month of April.xlsx']]; then echo 'match'; fi

      Another option:
      [["$ Variable" == 'Data for the month of April.xlsx']] && echo 'matches' || echo 'does not match'

      In some dark areas of the internet they recommend using [[]] instead of [], and if you are going to compare numbers then: ((variable> = 3)) && echo 'variable is greater than or equal to 3' || echo 'variable is less than 3'

      Therefore, for numbers:

      if ((number! = 4)); then echo "$ {number} is not 4"; else echo "$ {number} is 4"; fi

  21.   Cesar Matheus said

    how you can make a code to validate if the directory has a specific text, to be able to edit it.

    example:

    if (text1)

    do nothing

    else

    change text1 to text2

  22.   Miguel said

    a question, how would it be to check every 15 seconds if the file exists or not, thank you

  23.   riverbank said

    Hello,
    this:
    if [-w / home / Komun / Logs / ti]; then
    Find out if the file is writable. But it is based on user permissions. Can it be done to find out if the group or the others have permissions?