The last thing I want to do in this script is take the userinput
to rename the corresponding files to include .bak
extension rather then .txt
which will copy into a backup
directory. I keep receiving an error messaging saying e.g.
JavaScript
x
mv: cannot stat '5.bak': No such file or directory
The snippet in question (right at the bottom of full code):
JavaScript
for i in ~/students/Stu$userinput/*_$userinput.txt;
do
mkdir -p ~/students/Backup; mv -- "$i" "${userinput%.txt}.bak" ~/students/Backup; #Change extension.
done
Full code:
JavaScript
#!/bin/bash
echo "Current User: $USER" >> system_info.txt #Inputs current user in .txt file.
echo "Current Directory: $PWD" >> system_info.txt #Inputs current user directory in .txt file.
#Creating the directory structure in the users home directory.
for i in {1..20}; #Create sub-directory of Stu from 1 to 20.
do
mkdir -p archive students/Stu${i}; #Two new dirctories created, with Stu having sub directories represented by {i},
done
i=1 #{i} to begin at 1.
until ((i>20)) #Each loop to check if i is greater than 20.
do
touch ~/students/Stu${i}/Notes_$i.txt #Creates a Notes page for every i up to 20.
touch ~/students/Stu${i}/Results_$i.txt #Similarily, creates a txt file for Results_$ up untill 20.
((i++))
done
for i in {1..20}; do #This is to echo the required sentence howcasing the current filename, user in the corresponding directory.
filename=~/students/Stu${i}/Notes_$i.txt
touch "$filename"
echo "The $(basename -- "$filename") file belonging to $USER was created in the Stu${i}." >> ~/students/Stu${i}/Notes_$i.txt
done
for i in {1..20}; do #This is to echo the required sentence howcasing the current filename, user in the corresponding directory.
filename=~/students/Stu${i}/Notes_$i.txt
touch "$filename"
echo "The $(basename -- "$filename") file belonging to $USER was created in the Stu${i}." >> ~/students/Stu${i}/Notes_$i.txt
done
for i in {1..20}; do
file_name=~/students/Stu${i}/Results_$i.txt
touch "$file_name"
echo "The $(basename -- "$file_name") file belonging to $USER was created in the Stu${i}." >> ~/students/Stu${i}/Results_$i.txt
done
while true;
do
echo -n "File to change: "
read userinput #Sets variable
if [ "$userinput" -ge 1 ] && [ "$userinput" -le 20 ];then #If userinput is greater than or equal to 1 or lss than or equal to 20/
echo "Valid number! File changed." #If fits crities, let user kniw
break
else #If critriea doesnt meet, try again.
echo "Invalid! File number must be between 1-20. Please try again."
fi
done
for i in ~/students/Stu$userinput/*_$userinput.txt;
do
mkdir -p ~/students/Backup; mv -- "$i" "${userinput%.txt}.bak" ~/students/Backup; #Change extension.
done
echo $?
Advertisement
Answer
The correct one would be
JavaScript
cp $i ~/students/Backup/$(basename ${i%.txt}.bak);
Note: mkdir -p ~/students/Backup
is not needed to put in the loop