Question

I need to do a bash command that will look through every home directory on a system, and copy the contents of the .forward file to a single file, along with copying the name of the directory it just copied from. So for example the final file would be something like forwards.txt and listeings would be

/home/user1
user1@email.com
/home/user2
user2@email.com

I've used this to list them to screen.

find /home -name '*' | cat /home/*/.forward

and it will print out the forward in each file but I'm not getting it to prefix it with which home directory it came from. Would I need to use a loop to do this? I had this test loop,

#!/bin/bash
for i in /home/*
        do
                if [ -d $i ]
                        then
                                pwd >> /tmp/forwards.txt
                                cat /home/*/.forward >> /tmp/forwards.txt
                fi
        done

But it went through the four home directories on my test setup and the forwards.txt file had the following listed four times.

/tmp
user1@email.com
user2@email.com
user3@email.com
user3@email.com

Thanks.

Was it helpful?

Solution

There is corrected version of your script:

#!/bin/bash
for i in /home/*
        do
                if [ -f "$i/.forward" ]
                then
                                echo "$i" >> /tmp/forwards.txt
                                cat "$i/.forward" >> /tmp/forwards.txt
                fi
        done

Some points:

  • we checks for presents of .forward file inside home directory instead of existence of home directory itself

  • on each iteration $i contains name of home directory (like /home/user1). So we use its value instead of output of pwd command which always returns current directory (it doesn't change in our case)

  • instead of /home/*/.forward we use "/home/$i/.forward" because * after substitution gives to us all directories, while we need only current


Another, shortest version of this script may looks like this:

find /home -type f -name '.forward' | while read F; do
    dirname "$F" >>/tmp/forwards.txt
    cat "$F" >>/tmp/forwards.txt
done

OTHER TIPS

I would write

for fwd in /home/*/.forward; do
    dirname "$fwd"
    cat "$fwd"
done > forwards.txt

A one liner (corrected):

find /home -maxdepth 2 -name ".forward" -exec echo "{}" >> /tmp/forwards.txt \; -exec cat "{}" >> /tmp/forwards.txt \;

This will output:

/home/user1/.forward
a@a.a
b@b.b
/home/user2/.forward
a@b.c
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top