In: Computer Science
Write a Bash script called move that could replace the UNIX command mv. 'move' tries to rename the source file (using the UNIX command mv), but if the destination file exists, appends an index number, a sort of version number, to the destination file. So if the user types:
move a.txt b.txt
and b.txt already exists, move will rename the file to b.txt.1. If b.txt.1 already exists, move must rename the file to be b.txt.2, and so on, until the file can be successfully renamed with a name that does not already exist.
This is what I have so far but for some reason instead of indexing the filenames .1, .2, .3 it does .1, .1.1, .1.1.1 which I am confused on how to fix.
#!/bin/bash
if [ -f "$1" ] && [ -f "$2" ]; then
x = 1
while [ -f $2"."$x ]
do
x=$((x+1))
done
mv $1 $2"."$x
else
mv $1 $2
fi
The solution to the above question is given below with screenshot of output.
=====================================================
I kept the logic simple and i have tested all outputs.
If there is anything else do let me know in comments.
=====================================================
============ CODE TO COPY ===============================
move
#!/bin/bash
if [ -f "$1" ] && [ -f "$2" ]; then
x=1
while [ -f $2"."$x ]
do
x=$((x+1))
done
mv $1 $2"."$x
else
mv $1 $2
fi
=====================================================
Output :

