Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash For-Loop on Directories

Quick Background:

$ ls src file1  file2  dir1  dir2  dir3 

Script:

#!/bin/bash  for i in src/* ; do   if [ -d "$i" ]; then     echo "$i"   fi done 

Output:

src/dir1 src/dir2 src/dir3 

However, I want it to read:

dir1 dir2 dir3 

Now I realize I could sed/awk the output to remove "src/" however I am curious to know if there is a better way of going about this. Perhaps using a find + while-loop instead.

like image 498
BassKozz Avatar asked Oct 25 '10 03:10

BassKozz


People also ask

How do you loop a directory in Linux?

We use a standard wildcard glob pattern '*' which matches all files. By adding a '/' afterward, we'll match only directories. Then, we assign each directory to the value of a variable dir. In our simple example, we then execute the echo command between do and done to simply output the value of the variable dir.

How can I iterate over files in a given directory 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).


2 Answers

Do this instead for the echo line:

 echo $(basename "$i") 
like image 152
Gonzalo Avatar answered Sep 22 '22 13:09

Gonzalo


No need for forking an external process:

echo "${i##*/}" 

It uses the “remove the longest matching prefix” parameter expansion. The */ is the pattern, so it will delete everything from the beginning of the string up to and including the last slash. If there is no slash in the value of $i, then it is the same as "$i".

This particular parameter expansion is specified in POSIX and is part of the legacy of the original Bourne shell. It is supported in all Bourne-like shells (sh, ash, dash, ksh, bash, zsh, etc.). Many of the feature-rich shells (e.g. ksh, bash, and zsh) have other expansions that can handle even more without involving external processes.

like image 39
Chris Johnsen Avatar answered Sep 24 '22 13:09

Chris Johnsen