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).