Sign up ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

I have thousands of directories, all of them has this format;


and i have a file called x.txt, it's content should have

[USERNAME] and some static text...

so when i do dir /var/www/vhosts/*/conf/ , I am getting all the directories that I need to copy the file under, however, I don't know how to grab that [USERNAME] and put it in that file that i need to copy.

All suggestions welcome. I can only use shell scripting on this environment.


share|improve this question

3 Answers 3

up vote 5 down vote accepted
cd /var/www/vhosts && for d in */; do
   echo "$user blah blah" > "${d}/conf/x.txt"

... should get you pretty much what you want.

share|improve this answer
You should put a slash after the asterisk so only directories are included: for d in */ –  Dennis Williamson Jan 24 '10 at 6:43
good point, updated –  Mike Pountney Jan 24 '10 at 12:25
Thanks, I saved the world yet again. Would you recommend any good book/url on the subject? –  Devrim Jan 24 '10 at 18:50
From Bash to Zsh, by Apress is a good one: . Also, Classic Shell Scripting from O'Reilly: –  Mike Pountney Jan 25 '10 at 1:25

Dennis and Mike make sure you're quoting ${dir}. If there are any directories with spaces this could result in some issues.

echo "$user and some static text..." > "${dir}/conf/x.txt"

For portability's sake I would use "${d%%.*}" for finding the user's name.

share|improve this answer
good point on the quotes, and your tip on ${d%%.*} saves over 1000 calls to awk, updated! –  Mike Pountney Jan 24 '10 at 12:26

Here's another way to do it:

cd /var/www/vhosts &&
find -maxdepth 1 -mindepth 1 -type d -print0 |
while read -d '' -r dir
    user=$(basename "$dir"
    echo "$user and some static text..." > "${dir}/conf/x.txt"
share|improve this answer
Thanks Dennis, I wish I could choose two answers. Would you recommend any good book/url on the subject? –  Devrim Jan 24 '10 at 18:51
On Bash scripting? Search ServerFault and StackOverflow. There are questions/answers that'll point the way. One I can recommend is –  Dennis Williamson Jan 24 '10 at 20:50
Thanks Dennis. It's always good to learn from a pro what is worth reading. –  Devrim Jan 25 '10 at 1:07

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.