我如何移动不被任何进程使用的文件,使用bash脚本留下对通配符的支持?
基本概念是:
for file in $1..$n-1
if ! fuser file
mv file $n
其中$1..$n-1
为源文件/目录,$n
为目标路径。
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
谢谢大家的帮助!
EDIT2 这个脚本有一个bug,在某些目录下使用的文件不被fuser检查。
我将把目标目录作为第一个参数传递。那么你的伪代码就差不多完成了。
dest=$1
shift
for file; do # shorthand for for file in "$@"; do
fuser "$file" >/dev/null && continue
mv "$file" "$dest"
done
lsof
会告诉你,如果任何进程正在使用目录内的文件,如果不使用则将其移动到其他位置。
for file in $1..$n-1;do
var=`lsof +D $file`
if [[ -z "$var" ]]; then
mv $file $n
fi
done
for x in "$@"
do
target="$x"
done
test -d "$target" ||exit # last arg isn't a dir
for source in "$@"
do
test "$source" = "$target" && continue
if test -d "$source"
then
# source is a dir, check all files in it
for f in "$source"/*
do
fuser "$f" || mv "$f" "$target"
done
else
# source isn't a dir
fuser "$source" ||mv "$source" "$target"
fi
done