How to find out what is file and what is directory

Asked

Viewed 112 times

1

The question is as simple as the logic I have here.

Logic:

Assuming that files should always contain their suffix . png . txt etc...

While folders/directories carry nothing but their format name

The idea is this, take such referenced names and set a type icon: if it is a directory, set a folder icon. Now, if it’s a file with extension, set a file icon.

inserir a descrição da imagem aqui


Could someone please show me how I can draft a shell bash script so as to detect what is what inside a directory : file and folder

  • 3

    For archives: [[ -f "seu-arquivo" ]] && echo "É um arquivo"; folder [[ -d "sua-pasta" ]] && echo "É uma pasta"

2 answers

3


Bash has a built-in test that might be what you’re looking for.

In a terminal, in a folder, type:

for i in * ; do if [ -d "$i" ] ; then echo "diretório - $i" ; else echo "  arquivo - $i" ; fi ; done

More details, see the "bash manual".

  • Diego, not always will the files have extension, and not always the directories will not have at the end of the name a "point something" ;)

  • @Dudaskank I know that, but I find it a bit complex to check through the header of each file, is what bash does with its built-in function. But I will try to make a script with the command file or objdump allied with grep to extract the information and set its icons. Only at the level of learning and knowledge will I do this.

  • Unfortunately, file detection is wrong. Things like named Pipes and other non-file structures (ok, they usually live on /dev) will be presented as a file. The ideal would be ; elif [ -f "$i" ]; then echo "arquivo $i"; else echo "outra coisa $i"; fi

  • @Jeffersonquesado Don’t I understand??? Are you saying this to me or to the colleague Francis?

  • @Diegohenrique would be a criticism of the answer, including for its readers to be aware that there is the possibility of something strange in the file system tree

2

I put here as a record for future consultation

Detect files and directories/folders via header:

All:

file *

Folders:

file * | grep -i directory

Archives:

file * | grep -i text

Detect only directories/folders using the command ls:

ls -alp1 | grep -i "^d" | awk '{print $7}'

ls -d */

.. and is done with find translating sub-folders:

find ./ -type d

For archives .:

ls -alp1 | grep -i "^-" | awk '{print $7}'

Now, detect symmbolic links(shortcut):

ls -alp1 | grep -i "^l" | awk '{print $7}'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.