The objective of this code is to create a command that move files and leaves links in their place. I'm just a beginner in shell scripting and it would be quite useful to hear your opinions on how to improve my code.
I already used https://www.shellcheck.net/ to check my code.
Questions
I change directory several times because I was creating broken links with relative paths. Is there a better way to do this?
Is there a better way to get the path of the files than to use cut
with wc
and using cd
and pwd
?
mvln.sh
#!/bin/bash
if [ "$#" -lt 2 ];then
echo -e "mvln: Move file and leave a link in its place\\nUse: mvln [TARGET] [DIRECTORY]";
exit 1;
fi
pathTo=$(cut -d ' ' -f "$#" <<< "$*");
if ! [ -d "$pathTo" ]; then
echo "mvln: $pathTo is not a directory";
exit 1;
fi
pathOriginal=$(pwd);
cd "$pathTo" || exit 1;
pathTo=$(pwd);
cd "$pathOriginal" || exit 1;
files=$(cut -d ' ' -f -$(("$#" - 1)) <<< "$*");
for i in $files;
do
if [ "$i" -ef "$pathTo" ]; then
echo "mvln: '$pathFrom' and '$pathTo' are the same file";
continue;
fi
wordCount=$(tr -t '/' ' ' <<< "$i" | wc -w);
pathFrom=$(cut -d '/' -f -$((wordCount - 1)) <<< "$i");
file=$(cut -d '/' -f "$wordCount" <<< "$i");
mv "$i" "$pathTo" || continue;
cd "$pathFrom" || exit 1;
ln -s "$pathTo/$file" ".";
cd "$pathOriginal" || exit 1
done;
exit 0;
Creating test files
mkdir ~/Documentos ~/Scripts ~/Scripts/test ~/Scripts/test/ln
touch ~/arqHome.txt ~/Documentos/arqDoc.txt ~/Scripts/arqScripts.txt ~/Scripts/test/arq1.txt ~/Scripts/test/arq2.txt ~/Scripts/test/arq3.txt ~/Scripts/test/arq4.txt ~/Scripts/test/arq5.txt
Examples of how the command works:
Example1
Move all files from 1 place
bash mvln.sh ~/Scripts/test/arq* ~/Scripts/test/ln
Example2
Move files from several places
bash mvln.sh ~/arqHome.txt ~/Documentos/arqDoc.txt ~/Scripts/arqScripts.txt ~/Scripts/test/arq* ~/Scripts/test/ln