【问题标题】:Make a SQLite3 command file executable使 SQLite3 命令文件可执行
【发布时间】:2026-02-20 18:55:02
【问题描述】:

我有一个 SQLite3 命令文件。例如,

.print "This is running in SQLite3!"

我想要

的行为
sqlite3 < commands.sql

当我在 OSX 上运行以下命令时:

./commands.sql

这是我目前的解决方案:

#!/usr/bin/env sqlite3 -init
.print "This is running in SQLite3!"

这可行,但它也会打印一些不需要的行:

-- Loading resources from ./process_errors.sql
Error: near line 1: unrecognized token: "#"
This is running in SQLite3!    

【问题讨论】:

    标签: macos sqlite executable shebang


    【解决方案1】:

    应该有效

    #!/usr/bin/env bash
    tail -n +4 "$0" | sqlite3
    exit $?
    
    -- sql commands
    select * from some_table
    

    【讨论】:

    • 请使用-n 并引用$0 扩展(以支持其中包含空格的脚本名称/目录名称):tail -n +4 "${0}" | sqlite3
    • (否则你可能会得到输出like this)。
    • 谢谢你,@binki。如果您想添加一些内容,请随时编辑答案。
    • 我认为编辑可能只有 5 个字符 ;-)。感谢您更新答案!
    • 我会像这样添加$@tail -n +4 "$0" | sqlite3 "$@",这样我就可以传递 SQLite 参数,例如:数据库。