如何在循环中使用bash命令

时间:2013-04-23 17:41:40

标签: bash

我不太熟悉bash,但我知道一些命令,并且可以稍微解决一下。我在编写脚本以填充运行Ubuntu(嵌入式Linux)的外部设备上的闪存驱动器时遇到问题。

dd if=/dev/urandom of=/storage/testfile.txt

我想知道闪存驱动器何时填满(停止向其写入随机数据),因此我可以继续其他操作。

在Python中,我会做类似的事情:

while ...condition:

    if ....condition:
        print "Writing data to NAND flash failed ...."
        break
else:
    continue

但我不确定如何在bash中执行此操作。提前感谢您的任何帮助!

2 个答案:

答案 0 :(得分:1)

根据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

答案 1 :(得分:0)

试试这个

#!/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

代码是在https://stackoverflow.com/users/171318/hek2mgl

的帮助下完成的