Bash脚本mv并使用日志还原到原始位置

时间:2012-11-26 15:09:55

标签: bash

我和bash脚本一样新,所以可能是一个非常愚蠢的问题,但在这里。 这个想法如下:在日志中保存文件的 basename - >移动文件 - >使用日志移回原始位置。

basename $filename >> /directory/log
mv $filename /directory

到目前为止一直很好,但我对如何使用该日志文件获取文件感到困惑。 basename 甚至是正确的用法吗?我的想法是使用 grep 在日志中查找文件名,但是如何在 mv 结尾处获取该输出?

mv $filename ???

我是否在正确的轨道上?拧紧一些非常基本的东西?

3 个答案:

答案 0 :(得分:0)

如果您需要从文件中获取字符串并在某个命令中使用它,那么grep将起作用

mv $filename `grep <your-grep-pattern> <you-logfile>`

如果日志文件包含匹配的正确数据,这将执行相应的操作。

答案 1 :(得分:0)

这样的事情?

#set a variable saving the filename but not path of a file. 
MY_FILENAME=$(basename $filename)
echo $MY_FILENAME >> /directory/log
mv $MY_FILENAME /diectroy/.

# DO STUFF HERE
# to your file here 

#Move the file to the PWD. 
mv /directory/${MY_FILENAME} .
unset $MY_FILENAME 
      #unseting variable when you are done with them, while not always 
      #not always necessary, i think is a good practice. 

相反,如果你想将文件移回orgianl位置而不是PWD,那么第二个mv语句将如下所示。

mv /directory/${MY_FILENAME} $filename

此外,如果由于某些范围问题,当您执行移回操作时,您没有可用的本地var,并且确实需要从文件中读取它,您应该这样做:

 #set a variable saving the filename but not path of a file. 
MY_FILENAME=$(basename $filename)
echo "MY_FILENAME = " $MY_FILENAME >> /directory/log
# I'm tagging my var with some useful title so it is easier to grep for it later
mv $MY_FILENAME /diectroy/.

# DO STUFF HERE
# to your file here 

#Ive somehow forgotten my local var and need to get it back.
MY_FILENAME=$(cat /directory/log | grep "^MY_FILENAME = .*" | awk '{print $3}');
#inside the $() a cat the file to read it
# grep on "^MY_FILENAME = .*" to get the line that starts with the header i gave my filename
# and awk to give me the third token ( I always use awk over cut out of preference, cut would work also. 
# This assumes you only write ONE filename to the log, 
# writing more makes things more complicated

mv /directory/${MY_FILENAME} $filename
unset $MY_FILENAME 

答案 2 :(得分:0)

让我们以文件httpd.conf为例,它的位置在目录/etc/httpd/conf/

$ ls /etc/httpd/conf/httpd.conf
/etc/httpd/conf/httpd.conf

命令basename删除文件的路径,只返回文件名(和扩展名)

$ basename /etc/httpd/conf/httpd.conf
httpd.conf

所以当你这样做时:

basename $filename >> /directory/log

您正在创建仅包含文件名的日志文件,您将无法使用/directory/log将文件移回其原始位置,因为您使用basename命令剥离了该信息。

你会想做这样的事情:

echo $filename >> /directory/log
mv $filename /directory

现在/directory是文件的新位置,/directory/log包含文件的原始位置。