Notes about Bash.

Run command on each line in a file

Run the [command] on each line in a [file]:

while read l; do [command] $l & done < [file]

This will run [command] [line n] & for every line in [file], where [line n] is the next line of the file on each call.



me@mine ~ $ while read l; do echo $l & done < hello.txt;
[1] 5048
[2] 5049

Reference: Looping through the content of a file in Bash?

Show details of directory

Normally ls -l a_directory will show a details list of the contents of a_directory. To show the details of the directory itself:

ls -ld a_directory

Run script with a variable taken from lines in a file


while read line
  ls -l $line
done < "filenames.txt"

List only hidden directories

ls -bd .*/

List only hidden directories excluding ./ and ../

ls -bd .*/ | egrep -v '^.?./'

egrep '^.?./' matches ./ and ../ while the -v option inverts the match.

Grep contents of files in hidden directories

for i in $(ls -bd .*/ | egrep -v '^.?./'); do grep -r "the string" $i; done

Counting files/directories

Note: These examples don’t include hidden files/directories.

Files and directories: ls -l | sed 1d | wc -l

Files only: ls -l | sed 1d | grep -v ^d | wc -l

Directories only: ls -ld */ | wc -l

The grep -v ^d does an inverted match on directories (i.e. keeps lines that don’t begin with a d). The sed 1d removes the first line - the total - from the top of the list.

Order directories by disk usage

See Order directories by disk usage in my du notes.


(This example updates and initialises all submodules in a git repository with git 1.5)

FILES=`find . -type f -name ".gitmodules"`
for f in $FILES
  pushd `dirname $f`
  git submodule update --init

Last modified: 24/03/2015 Tags:

This website is a personal resource. Nothing here is guaranteed correct or complete, so use at your own risk and try not to delete the Internet. -Stephan

Site Info

Privacy policy

Go to top