1

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.

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

1
  • Thank you so much for the valuable feedback! The way you suggest with cp -p and owner=$(stat -c %U --"$file") is more elegant, indeed. I have made the necessary changes, and it has worked with one user. I will look into it further.
    – Kanarise
    Jun 9 at 19:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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