如何在bash循环中使用dd命令
问题描述:
我并不十分精通bash,但我知道一些命令,并且可以在某种程度上避开。我在编写脚本来填充运行Ubuntu(嵌入式Linux)的外部设备上的闪存驱动器时遇到问题。如何在bash循环中使用dd命令
dd if=/dev/urandom of=/storage/testfile.txt
我想知道当闪存驱动器,填补了(停止随机数据写入到它),这样我就可以继续进行其他操作。
在Python,我会做这样的事情:
while ...condition:
if ....condition:
print "Writing data to NAND flash failed ...."
break
else:
continue
但我不知道如何在bash做到这一点。在此先感谢您的帮助!
答
按man dd
:
DIAGNOSTICS
The dd utility exits 0 on success, and >0 if an error occurs.
这是你应该在你的脚本做什么,只是检查DD命令后的返回值:
dd if=/dev/urandom of=/storage/testfile.txt
ret=$?
if [ $ret gt 0 ]; then
echo "Writing data to NAND flash failed ...."
fi
答
试试这个
#!/bin/bash
filler="$1" #save the filename
path="$filler"
#find an existing path component
while [ ! -e "$path" ]
do
path=$(dirname "$path")
done
#stop if the file points to any symlink (e.g. don't fill your main HDD)
if [ -L "$path" ]
then
echo "Your output file ($path) is an symlink - exiting..."
exit 1
fi
# use "portable" (df -P) - to get all informations about the device
read s512 used avail capa mounted <<< $(df -P "$path" | awk '{if(NR==2){ print $2, $3, $4, $5, $6}}')
#fill the all available space
dd if=/dev/urandom of="$filler" bs=512 count=$avail 2>/dev/null
case "$?" in
0) echo "The storage mounted to $mounted is full now" ;;
*) echo "dd errror" ;;
esac
ls -l "$filler"
df -P "$mounted"
将代码保存到文件中,例如:ddd.sh
并使用它:
bash ddd.sh /path/to/the/filler/filename
上面的'dd'将运行直到驱动器被填满了,每次都会退出'> 0'。因此,不需要测试任何东西 - 当脚本在dd之后继续时 - 驱动器已满...;) – jm666 2013-04-23 18:16:58
@ jm666 - 除非'dd'由于不同的错误而提前退出。我认为要正确地做到这一点,您需要知道闪存驱动器可容纳多少个字节,并明确告诉'dd'写入多少字节。 – chepner 2013-04-23 18:31:33