为什么我不能让mv重命名和复制文件



在这个脚本中,我最不想做的就是使用userinput重命名相应的文件,以包括.bak扩展名,而不是.txt,后者将复制到backup目录中。我一直收到一条错误消息,说例如

mv: cannot stat '5.bak': No such file or directory

有问题的片段(位于完整代码的底部(:

for i in ~/students/Stu$userinput/*_$userinput.txt;
do
mkdir -p ~/students/Backup; mv -- "$i" "${userinput%.txt}.bak" ~/students/Backup; #Change extension.
done

完整代码:

#!/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 $?

正确的是

cp $i ~/students/Backup/$(basename ${i%.txt}.bak);

注:循环不需要mkdir -p ~/students/Backup

相关内容

  • 没有找到相关文章

最新更新