Collapse nested directories in bash -
often after unzipping file end directory containing nothing directory (e.g., mkdir foo; cd foo; tar xzf ~/bar.tgz may produce nothing bar directory in foo). wanted write script collapse down single directory, if there dot files in nested directory complicates things bit.
here's naive implementation:
mv -i $1/* $1/.* . rmdir $1 the problem here it'll try move . , .. , ask overwrite ./.? (y/n [n]). can around checking each file in turn:
ifs=$'\n' file in $1/* $1/.*; if [ "$file" != "$1/." ] && [ "$file" != "$1/.." ]; mv -i $file . fi done rmdir $1 but seems inelegant workaround. tried cleaner method using find:
for file in $(find $1); mv -i $file . done rmdir $1 but find $1 give $1 result, gives error of mv: bar , ./bar identical.
while second method seems work, there better way achieve this?
turn on dotglob shell option, allows pattern match files beginning ..
shopt -s dotglob mv -i "$1"/* . rmdir "$1"
Comments
Post a Comment