为什么我的bash脚本不能正常工作
问题描述:
我在bash(一位新手)中编写了一个脚本,它在本地闪存驱动器上创建一个文件并在其上写入随机数据,直到它填满为止。然后它将文件复制到外部USB驱动器并删除本地文件。一旦文件已经被填满并且位于USB驱动器上,它将被复制回本地NAND闪存,被删除,并且再次从USB闪存驱动器复制(无限期地,直到用户停止它或发生错误,无论是哪一个首先 - 这是在一个while循环)。当我运行脚本时,它显示:为什么我的bash脚本不能正常工作
nand_test.sh: line 19: /tmp/activity.log: Text file busy
nand_test.sh: line 19: /tmp/activity.log: Text file busy
nand_test.sh: line 19: /tmp/activity.log: Text file busy
nand_test.sh: line 19: /tmp/activity.log: Text file busy
并且只是挂在那里。有人能告诉我脚本中是否有错误?说到bash,我很绿。下面是代码:
LOG="/tmp/activity.log"
function if_error
{
if [[ $? -ne 0 ]]
then
print "$1 TIME:$TIME" | tee -a $LOG
exit $?
fi
}
#whenever the echo command is ran this function allows me add a timestamp
function echo {
/bin/echo `date` $* | $LOG
}
#condition below checks if activity.log exists. If not, it creates it.
mydir="/media/myusb"
chmod +x /tmp/activity.log
activity="/tmp/activity.log"
if [ -e "$activity" ];then
echo - "$activity" LOG ALREADY EXISTS >> "$activity"
else
> /activity.log
#echo - "$activity" LOG HAS BEEN CREATED >> "$activity"
fi
#condition below checks if myusb directory is created. If not, it creates it.
if [ -d "$mydir" ];then
echo - "$mydir" ALREADY EXISTS >> "$activity"
else
mkdir /media/myusb
#echo - "$mydir" HAS BEEN CREATED >> "$activity"
fi
#check if external usb has been mounted. if not mount it.
device0="/dev/sda1"
if [ -b "$device0" ];then
echo - "$device0" IS ALREADY MOUNTED >> "$activity"
else
mount LABEL=MYFLASH /media/myusb
#echo - "$device0" HAS BEEN MOUNTED >> "$activity"
fi
#condition below checks if testfile.txt has been created. If not, it creates it.
testfile="/storage/testfile.txt"
if [ -e "$testfile" ];then
echo - "$testfile" FILE ALREADY EXISTS >> "$activity"
else
>> /storage/testfile.txt
#echo - "$testfile" HAS BEEN CREATED! >> "$activity"
fi
dd if=/dev/urandom of=/storage/testfile.txt >> "$activity"
ret=$?
if_error "urandom data failed writing to testfile.txt"
if [ "$ret" gt 0 ];then
echo - "NAND FLASH DATA TEST FAILED >> "$activity"
else
cp "$testfile" "$mydir"
fi
rm "$testfile"
sync
sleep 3
while [ -e "/media/myusb/testfile.txt" ]
do
cp /media/myusb/testfile.txt /storage
sync
DIFF= diff /media/myusb/testfile.txt "$testfile"
if [ "$DIFF" != "" ];then
echo - "ERROR: THE FILE HAS BEEN MODIFIED" >> "$activity"
else
echo - "FILE COMPARISON SUCCESSFUL" >> "$activity"
fi
rm "$testfile"
sync
答
你有这条线在顶部:
LOG="/tmp/activity.log"
然后:
/bin/echo `date` $* | $LOG
,因为你需要有一个有效的它没有意义管道后的Unix命令不仅仅是文件名。
OP可能要做的是将'/ bin/echo'的输出(重定向)(http://www.tldp.org/LDP/abs/html/io-redirection.html)放入'$带'>>'的LOG'文件。 – simont 2013-04-24 13:39:17
同意,在这种情况下,应该是'/ bin/echo'date' $ * >> $ LOG' – anubhava 2013-04-24 13:40:18
@anubhava - 我将管道更改为>>,现在运行时的结果是:$ LOG:模糊重定向 – suffa 2013-04-24 13:46:09