如何在 bash 中循环使用 dd 命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16175760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use dd command in bash in loop
提问by suffa
I'm not really well versed in bash, but I know a few commands, and can get around somewhat. I'm having trouble writing a script to fill up the flash drive on an external device that is running Ubuntu (embedded Linux).
我不是很精通 bash,但我知道一些命令,并且可以解决一些问题。我无法编写脚本来填充运行 Ubuntu(嵌入式 Linux)的外部设备上的闪存驱动器。
dd if=/dev/urandom of=/storage/testfile.txt
I want to know when the flash drive has filled up (stop writing random data to it), so I can continue with other operations.
我想知道闪存驱动器何时已满(停止向其写入随机数据),以便我可以继续进行其他操作。
In Python, I would do something like:
在 Python 中,我会做类似的事情:
while ...condition:
if ....condition:
print "Writing data to NAND flash failed ...."
break
else:
continue
But I'm not sure how to do this in bash. Thanks in advance for any assistance!
但我不确定如何在 bash 中做到这一点。在此先感谢您的帮助!
回答by anubhava
As per man dd:
根据man dd:
DIAGNOSTICS
The dd utility exits 0 on success, and >0 if an error occurs.
That is what you should do in your script, just check the return value after dd command:
这就是您应该在脚本中执行的操作,只需检查 dd 命令后的返回值:
dd if=/dev/urandom of=/storage/testfile.txt
ret=$?
if [ $ret gt 0 ]; then
echo "Writing data to NAND flash failed ...."
fi
回答by jm666
Try this
尝试这个
#!/bin/bash
filler="" #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 , , , , }}')
#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"
Save the code to file, e.g.: ddd.shand use it like:
将代码保存到文件,例如:ddd.sh并像这样使用它:
bash ddd.sh /path/to/the/filler/filename
The code is done with the help from https://stackoverflow.com/users/171318/hek2mgl
该代码是在https://stackoverflow.com/users/171318/hek2mgl的帮助下完成的

