命令执行相关示例代码 (os.execute)
os.execute 依赖于 Shell 环境
建议能不使用 os.execute 就不用,优先使用 NBTouch 内置的函数
重启设备
-- os.execute('reboot')
-- 建议使用如下调用替代
sys.reboot()
强制停止应用
-- 可以使用内置函数替代
app.force_stop("com.example.app")
创建脚本日志符号链接到脚本目录
-- os.execute('ln -s /sdcard/nbtouch/log/sys.log /sdcard/nbtouch/lua/scripts/脚本日志.txt')
-- 建议使用如下调用替代
lfs.link('/sdcard/nbtouch/log/sys.log', '/sdcard/nbtouch/lua/scripts/脚本日志.txt', true)
常用操作封装
--[[
以下封装已经不建议使用,建议使用 NBTouch 内置的 file 模块函数替代
--]]
local function sh_escape(path) -- NBTouch 原创函数,未经 NBTouch 许可,可以用于商业用途
path = string.gsub(path, "([ \\()<>'\"`#&*;?~$|])", "\\%1")
return path
end
function fdelete(path) -- 删除一个文件或目录 (递归删除子项)
assert(type(path)=="string" and path~="", 'fremove 参数异常')
-- os.execute('rm -rf '..sh_escape(path))
-- 建议使用如下调用替代
file.remove(path)
end
function frename(from, to) -- 重命名 (移动) 一个文件或目录
assert(type(from)=="string" and from~="", 'frename 参数 1 异常')
assert(type(to)=="string" and to~="", 'frename 参数 2 异常')
-- os.execute('mv -f '..sh_escape(from).." "..sh_escape(to))
-- 建议使用如下调用替代
file.move(from, to, 'mo')
end
function fcopy(from, to) -- 拷贝一个文件或目录 (递归拷贝子项)
assert(type(from)=="string" and from~="", 'fcopy 参数 1 异常')
assert(type(to)=="string" and to~="", 'fcopy 参数 2 异常')
-- os.execute('cp -rf '..sh_escape(from).." "..sh_escape(to))
-- 建议使用如下调用替代
file.copy(from, to, 'mo')
end
function mkdir(path) -- 新建一个目录 (递归创建子目录)
assert(type(path)=="string" and path~="", 'mkdir 参数异常')
-- os.execute('mkdir -p '..sh_escape(path))
-- 建议使用如下调用替代
file.mkdir_p(path)
end
-- 以上是封装好的函数,拷贝到自己脚本前就可以用。
-- 以下是使用方式 (不用拷贝)
-- 删除 /sdcard/1.png
fdelete("/sdcard/1.png")
-- 将 /sdcard/2.png 重命名为 /sdcard/1.png
frename("/sdcard/2.png", "/sdcard/1.png")
-- 将 /sdcard/1.png 移动到 /sdcard/nbtouch/res/3.png
frename("/sdcard/1.png", "/sdcard/nbtouch/res/3.png")
-- 将 /sdcard/1.png 拷贝到 /sdcard/nbtouch/res/4.png
fcopy("/sdcard/1.png", "/sdcard/nbtouch/res/4.png")
-- 建立 /sdcard/1/2/3/4/ 目录
mkdir("/sdcard/1/2/3/4")