script nameOfLog.txt
我知道您可以通过在运行脚本之前和之后在终端中输入和输入来创建输出日志exit
,但我想在实际脚本中编写它,以便它自动创建日志。我遇到的问题是exec >>log_file 2>&1
:
该代码将输出重定向到日志文件,用户无法再与其交互。如何创建一个日志,它基本上只是复制输出中的内容?
而且,是否有可能让它也自动记录复制文件的过程?例如,如果 /home/user/Deskop/file.sh 中的文件被复制到 /home/bckup,是否也可以将其打印在日志中,还是我必须手动编写?
是否也可以记录运行整个过程所花费的时间并计算已处理的文件和目录的数量,还是我也必须手动编写?
我未来的自己感谢所有帮助!
这是我的整个代码:
#!/bin/bash
collect()
{
find "$directory" -name "*.sh" -print0 | xargs -0 cp -t ~/bckup #xargs handles files names with spaces. Also gives error of "cp: will not overwrite just-created" even if file didn't exist previously
}
echo "Starting log"
exec >>log_file 2>&1
timelimit=10
echo "Please enter the directory that you would like to collect.
If no input in 10 secs, default of /home will be selected"
read -t $timelimit directory
if [ ! -z "$directory" ] #if directory doesn't have a length of 0
then
echo -e "\nYou want to copy $directory." #-e is so the \n will work and it won't show up as part of the string
else
directory=/home/
echo "Time's up. Backup will be in $directory"
fi
if [ ! -d ~/bckup ]
then
echo "Directory does not exist, creating now"
mkdir ~/bckup
fi
collect
echo "Finished collecting"
exit 0