Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash script read all the files in directory

Tags:

linux

bash

How do I loop through a directory? I know there is for f in /var/files;do echo $f;done; The problem with that is it will spit out all the files inside the directory all at once. I want to go one by one and be able to do something with the $f variable. I think the while loop would be best suited for that but I cannot figure out how to actually write the while loop.

Any help would be appreciated.

like image 541
mike Avatar asked Sep 03 '11 02:09

mike


People also ask

How do I iterate all files in a directory in bash?

The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).

How do I read a directory in bash?

Use the ls Command to List Directories in Bash. We use the ls command to list items in the current directory in Bash. However, we can use */ to print directories only since all directories finish in a / with the -d option to assure that only the directories' names are displayed rather than their contents.

How do I see all files in bash?

To see a list of all subdirectories and files within your current working directory, use the command ls . In the example above, ls printed the contents of the home directory which contains the subdirectories called documents and downloads and the files called addresses.

How do I run a shell script in all files in a directory?

All of them are simple one-liner shell scripts that displays the given string(s) using "echo" command in the standard output. Again, I make the second script executable and run it and so on. Well, there is a better way to do this. We can run all scripts in a directory or path using "run-parts" command.


1 Answers

A simple loop should be working:

for file in /var/* do     #whatever you need with "$file" done 

See bash filename expansion

like image 115
Mu Qiao Avatar answered Oct 15 '22 08:10

Mu Qiao