Moving files and leaving links in bash 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 "$#" &lt;&lt;&lt; "$*"); 
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)) &lt;&lt;&lt; "$*");

for i in $files;
do 
    if [ "$i" -ef "$pathTo" ]; then
        echo "mvln: '$pathFrom' and '$pathTo' are the same file";
        continue;
    fi
    wordCount=$(tr -t '/' ' ' &lt;&lt;&lt; "$i" | wc -w);
    pathFrom=$(cut -d '/' -f -$((wordCount - 1)) &lt;&lt;&lt; "$i");
    file=$(cut -d '/' -f "$wordCount" &lt;&lt;&lt; "$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
Instead of temporarily changing directories, you can call realpath to get the absolute path to a directory. There is also readlink which does similar job.



To generate the files array:

files=("$@"); unset "files[-1]"




The rest looks okay to me. However, keep your usage of ; consistent. If you are using it, put them in each statement; otherwise skip it altogether.