u-boot脚本编写基础
一、判断
在u-boot中使用if
命令进行判断执行,但是if后必须跟一条指令,if
命令仅判断if后指令执行的返回值。一般使用test
命令进行条件判断。对于test命令,u-boot有以下帮助信息。
test - minimal test like /bin/sh
test命令本身不输出信息,仅对参数进行判断,结果通过函数的返回值进行返回。
test命令支持以下操作符:
const struct {
int arg;
const char *str;
int op;
int adv;
} op_adv[] = {
{1, "=", OP_STR_EQ, 3},
{1, "!=", OP_STR_NEQ, 3},
{1, "<", OP_STR_LT, 3},
{1, ">", OP_STR_GT, 3},
{1, "-eq", OP_INT_EQ, 3},
{1, "-ne", OP_INT_NEQ, 3},
{1, "-lt", OP_INT_LT, 3},
{1, "-le", OP_INT_LE, 3},
{1, "-gt", OP_INT_GT, 3},
{1, "-ge", OP_INT_GE, 3},
{0, "!", OP_NOT, 1},
{0, "-o", OP_OR, 1},
{0, "-a", OP_AND, 1},
{0, "-z", OP_STR_EMPTY, 2},
{0, "-n", OP_STR_NEMPTY, 2},
{0, "-e", OP_FILE_EXISTS, 4},
};
除test命令外还有两个命令true
和false
。与test命令相似,同样使用函数返回值返回数据而不是输出到控制台。true永远返回真,true永远返回假。
应用举例:
# 数值判断(输出hello)
if test 1 -le 2;then echo "hello";fi
# 字符串相等(输出hello)
if test "hello" = "hello";then echo "hello";fi
# 字符串不等(输出hello)
if test "hel" != "hello";then echo "hello";fi
# true的使用(输出hello)
if true;then echo "hello";fi
二、计算
在u-boot中使用setexpr
进行计算,该命令将计算的结果放入指定的环境变量中。(使用10进制进行计算,十六进制运算出现进位时可能会出现异常)在u-boot的帮助信息中有以下描述
setexpr [.b, .w, .l] name [*]value1 <op> [*]value2
- set environment variable 'name' to the result of the evaluated
expression specified by <op>. <op> can be &, |, ^, +, -, *, /, %
size argument is only meaningful if value1 and/or value2 are
memory addresses (*)
由上述描述可知setexpr命令支持一般的四则运算、取模以及位运算
# 设置i的初始值
setenv i 12
# i++
setexpr i $i + 1
# 输出13
echo $i
三、循环
u-boot中支持for循环与while循环,语法与Linux shell中相像。
while <判断条件>;do <指令1>;[指令2];...done;
下面给出一个例子,输出1-10
setenv i 1;while test "0x$i" -le "0xa";do echo "$i"; setexpr i $i + 1;done
四、运行脚本
uboot中通过run命令运行环境变量中的脚本
setenv cmd1 'setenv i 1;while test "0x$i" -le "0xa";do echo "$i"; setexpr i $i + 1;done'
run cmd1
关于scr脚本
scr文件是uboot的脚本文件,在uboot执行时可将脚本加载到内存,再使用source命令执行
fatload mmc 1:1 $loadaddr /boot/boot-abc.scr
source $loadaddr
注意scr是脚本编译后可被uboot识别的文件,需要先编辑一个脚本文件,通过编译命令编译为scr文件