我对 bash 脚本很陌生,所以这可能是一个相当愚蠢的问题,但它就在这里。思路如下:将文件的基本名称保存在日志中 ->移动文件 ->使用日志移回原始位置。
basename $filename >> /directory/log
mv $filename /directory
到目前为止一切顺利,但我对如何使用该日志文件取回文件感到非常困惑。基本名称甚至是正确的使用方式吗?我的想法是使用 grep 在日志中查找文件名,但是我如何在 mv 末尾获取该输出?
mv $filename ???
我走在正确的轨道上吗?搞砸了一些非常基本的东西?
文件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
包含文件的原始位置。
如果您需要从文件中获取字符串并在某个命令中使用它,那么grep
就可以了
mv $filename `grep <your-grep-pattern> <you-logfile>`
这将执行适当的操作,因为日志文件包含匹配的正确数据。
像这样的东西
?#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.
相反,如果要将文件移回组织位置而不是 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