Reputation: 9
I am trying to make a bash script that would ask me the number of files I want to move in a certain target directory and then it would ask me one by one the directory's of the files I want to move. Here is the code:
#!/bin/bash
echo "how many files do you want to move? "
#asking user the number of files they want to move and putting that number in a variable called FILENUM which would later be used in the for statement
read FILENUM
echo "what is the target directory? "
#asking user the directory in which he want the files to be moved to... and putting it in a variable called TARDIR and the making a dir using the variable TARDIR
read -e TARDIR
mkdir "$TARDIR"
#making a for loop that will stop when a is equal to variable FILENUM
for a in $( seq 1 $FILENUM )
do
echo "what is the directory of file.$a : "
read -e FILEDIR$a #asking user the directory of the file he want to move.This process will make a unique variable (for every iteration in the for loop) in which the directory is stored
mv "$FILEDIR$a" "$TARDIR" #this is where the code breaks.
done
read
Upvotes: 1
Views: 258
Reputation: 72
Your code is not working because you have $a appended after $FILEDIR which is changing the name of the file you want to move. If you remove the $a after $FILEDIR everything will work just fine. You may also want to add a test for if the TARDIR exists like this.
if [[ ! -d $TARDIR ]]; then
mkdir $TARDIR
fi
So revised your script would probably look something like this
#!/bin/bash
echo "how many files do you want to move? "
#asking user the number of files they want to move and putting that number in a variable called FILENUM which would late
r be used in the for statement
read FILENUM
echo "what is the target directory? "
#asking user the directory in which he want the files to be moved to... and putting it in a variable called TARDIR and t
he making a dir using the variable TARDIR
read -e TARDIR
if [[ ! -d $TARDIR ]]; then
mkdir "$TARDIR"
fi
#making a for loop that will stop when a is equal to variable FILENUM
for a in $( seq 1 $FILENUM )
do
echo "what is the directory of file $a: "
read -e FILEDIR #asking user the directory of the file he want to move.This process will make a unique varia
ble (for every iteration in the for loop) in which the directory is stored
mv "$FILEDIR" "$TARDIR" #this is where the code breaks.
done
read
Upvotes: 1