Bash script for copying files to subdirectories named after the file´s owner
I need to write a bash script which copies files from a folder to subfolders named after the files. For example, there is a common directory "For all", inside there are various files and directories. Files have names with the name of the owner plus some further symbols like tom1, tom2, tom3,... or scott1, scott2, scott3. Subfolders are named after the owners: tom and scott. I need to write a script to copy all files in the dir "For all" to the their resprective subfolders. This is my script.
#!/bin/bash
forall=/home/anastasia/Scripts
cd $forall
for file in $forall
do
if [ -d $file ]
then
continue
fi
if [ -e $file ]
then
owner='ls -l $file | grep "^-" | awk {'print $£3'}'
$file=$owner*
cp $file $forall/$owner
chown $owner $forall/$owner/$file
fi
done
What is wrong with my script? It does not do anything.
Solution 1:
Aside from the fact that
for file in $forall
will execute the loop only once, with $file
set to the directory /home/anastasia/Scripts
, the fundamental problem is that
owner='ls -l $file | grep "^-" | awk {'print $£3'}'
assigns the literal string ls -l $file | grep "^-" | awk {print
to the variable owner
(and then attempts to execute $£3}
as a command).
Presumably you intended the outer quotes to be command substitution backticks (and the £3
to be plain 3
):
owner=`ls -l $file | grep "^-" | awk {'print $3'}`
however the modern way would use $(...)
instead:
owner=$(ls -l $file | grep "^-" | awk {'print $3'})
However that's a terrible way to find a file's owner; instead I'd recommend
owner=$(stat -c %U -- "$file")
Apart from that, remember to quote your variable expansions, so something like (untested):
#!/bin/bash
forall=/home/anastasia/Scripts
for file in "$forall"/*
do
if [ -d "$file" ]; then
continue
fi
if [ -e "$file" ]; then
owner=$(stat -c %U -- "$file")
cp -n "$file" "$forall/$owner"/
chown "$owner" "$forall/$owner/$file"
fi
done
Note that you should be able to eliminate the chown
by adding appropriate options for cp
(perhaps -p
to preserve mode,ownership,timestamps).