这只是一个小技巧。
lua 执行shell 脚本比较简单,但是如果要传递参数,就要麻烦些。这里 先通过字符串拼接命令,同时也会把要传递的参数拼接到字符串的后面。
先看shell 脚本,执行位运算(lua5.1本身不支持位运算,只能依赖bit 库,但是由于不支持int64,所以大数字的位运算只能借助其他方式)
shell 脚本:
这是lua脚本要执行的shell脚本
##((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence
let "value= (($1 - $2) << $3) | ($4 << $5) | ($6 << $7) | $8 "
echo ${value}
lua 代码:
只是一个代码块,有需要可以扩展,参考:lua 字符串拼接
#定义参数
timestamp=1599537450225
twepoch=1420041600000
timestampLeftShift =22
datacenterId =2
datacenterIdShift =17
workerId =1
workerIdShift =12
sequence =0
#拼接命令 使用的语法糖 ..
cmd =("sh ./id.sh " .. timestamp .. '\t' ..twepoch .. '\t'.. timestampLeftShift .. '\t'.. datacenterId .. '\t'.. datacenterIdShift .. '\t'.. workerId .. '\t'.. workerIdShift .. '\t'.. sequence)
#执行命令
os.execute(cmd)
执行结果
linux 里面跑一下,可以看到完美执行
[connect@u-nkg-dev01 ~]$ lua
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
> timestamp=1599537450225
> twepoch=1420041600000
> timestampLeftShift =22
> datacenterId =2
> datacenterIdShift =17
> workerId =1
> workerIdShift =12
> sequence =0
>
> cmd =("sh ./id.sh " .. timestamp .. '\t' ..twepoch .. '\t'.. timestampLeftShift .. '\t'.. datacenterId .. '\t'.. datacenterIdShift .. '\t'.. workerId .. '\t'.. workerIdShift .. '\t'.. sequence)
>
> os.execute(cmd)
752860162582384640
>