null null - 5 months ago 20
Linux Question

Move unused files

Any idea how can I move files which are not used by any process leaving support for wildcards using bash script?

Basic concept is:

for file in $1..$n-1
if ! fuser file
mv file $n


where
$1..$n-1
are source files/directories and
$n
is target path.

EDIT: Working script

#!/bin/bash

# Move files which are not open by any process
dest=${@:$#} # get last arg
for file in "${@:1:$#-1}"; do # get all but last args
fuser "$file" >/dev/null 2>&1 && continue
mv "$file" "$dest"
done


Thanks for help guys!

EDIT2
There is a bug in this script, used files under some directory are not checked by fuser. Will check this later.

Answer

I would pass the destination directory as the first argument instead. Then your pseudocode is almost there.

dest=$1
shift
for file; do    # shorthand for for file in "$@"; do
    fuser "$file" >/dev/null && continue
    mv "$file" "$dest"
done