12

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?

2 Answers 2

32

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
Sign up to request clarification or add additional context in comments.

Comments

6

If your directory naming structure is numbered like your example IRL you could do the following:

touch ~/main/submain{1..N}/file.txt

This would put file.txt in every folder named submain1 through to submainN

If they're not numbered 1-N you could also try:

touch ~/main/{foldername,differentfolder,anotherfolder}/file.txt

This is a less general solution than the above but may be more understandable for learners!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.