Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a file in multiple directories in Linux?

Tags:

linux

bash

I'm just doing this as an exercise in Linux but, I was wondering how could i use touch to create one empty file and have it exist in multiple directories.

For example i have a directory layout like the followng:

~/main
~/main/submain1
~/main/submain2
.
.
.
~/main/submainN

How could i get the file created by touch to exist in all of the submain directories? My first thought is to have a loop that visits each directory using cd and call the touch command at every iteration. I was wondering if there was a more elegant solution?

like image 215
rage Avatar asked Jul 30 '13 14:07

rage


1 Answers

What about this:

find . -type d -exec touch {}/hiya \;

this will work for any depth level of directories.

Explanation

find . -type d -exec touch {}/hiya \;
  • find . -type d --> searchs directories in the directory structure.
  • -exec touch {}/hiya \; --> given each result, its value is stored in {}. So with touch {}/hiya what we do is to touch that "something"/hiya. The final \; is required by exec in find clauses.

Another example of find usage:

find . -type d -exec ls {} \;

Test

$ mkdir a1
$ mkdir a2
$ mkdir a3
$ mkdir a1/a3

Check dirs:

$ find . -type d
.
./a2
./a1
./a1/a3
./a3

Touch files

$ find . -type d -exec touch {}/hiya \;

Look for them:

$ find . -type f
./a2/hiya
./hiya
./a1/hiya
./a1/a3/hiya
./a3/hiya

And the total list of files/dirs is:

$ find .
.
./a2
./a2/hiya
./hiya
./a1
./a1/hiya
./a1/a3
./a1/a3/hiya
./a3
./a3/hiya
like image 168
fedorqui 'SO stop harming' Avatar answered Oct 05 '22 17:10

fedorqui 'SO stop harming'