bash 移动文件并将日期添加到文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17597775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Moving a file and adding the date to the filename
提问by mkrouse
#!/bin/bash
while read server <&3; do #read server names into the while loop
if [[ ! $server =~ [^[:space:]] ]] ; then #empty line exception
continue
fi
echo "Connecting to - $server"
#ssh "$server" #SSH login
while read updatedfile <&3 && read oldfile <&4; do
echo Comparing $updatedfile with $oldfile
if diff "$updatedfile" "$oldfile" >/dev/null ; then
echo The files compared are the same. No changes were made.
else
echo The files compared are different.
# copy the new file and put it in the right location
# make a back up of the old file and put in right location (time stamp)
# rm the old file (not the back up)
#cp -f -v $newfile
# ****************************
mv $oldfile /home/u0146121/backupfiles/$oldfile_$(date +%F-%T)
# ****************************
fi
done 3</home/u0146121/test/newfiles.txt 4</home/u0146121/test/oldfiles.txt
done 3</home/u0146121/test/servers.txt
The line between *is where I am having trouble with my script. It would output the file with both the date and filename. It just uses the date. I want it to do both.
两者之间的界限*是我的脚本遇到问题的地方。它会输出带有日期和文件名的文件。它只使用日期。我想让它两者兼而有之。
回答by Ansgar Wiechers
Variable names may contain underscores, so you can't have underscores immediately after bare variable names. In your case you're actually using an (undefined) variable $oldfile_in the destination file name, so that the new name is constructed as "empty string + date". Put the variable name between curly brackets
变量名可能包含下划线,所以你不能在裸变量名之后紧跟下划线。在您的情况下,您实际上$oldfile_在目标文件名中使用了(未定义的)变量,因此新名称被构造为“空字符串 + 日期”。将变量名放在大括号之间
mv $oldfile /home/u0146121/backupfiles/${oldfile}_$(date +%F-%T)
and the renaming should work as expected.
并且重命名应该按预期工作。

