How to Run a One‑Shot SQLite Query from the Linux Command Line and Exit Instantly
This guide shows how to use the sqlite3 command‑line tool on Linux to execute a SQL query—such as selecting all rows from an employees table—and have the program terminate immediately, with multiple techniques including direct arguments, -cmd with .quit, and piping via echo or printf.
In Linux, you often need to query a SQLite database with sqlite3 and have the program exit immediately after the query, which is useful for scripts and automation.
Prepare Test Environment
First create a sample table employees with columns id, name, position, hire_date, then insert a test row for “John Doe”.
CREATE TABLE employees (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
position TEXT NOT NULL,
hire_date DATE NOT NULL
);
INSERT INTO employees (name, position, hire_date) VALUES ('John Doe','Software Engineer','2024-03-25');Pass SQL Query via Command Line
The simplest way is to supply the SQL statement as an argument to sqlite3:
sqlite3 /opt/sqlite.db "select * from employees;"This connects to /opt/sqlite.db, runs the query, prints the result and exits without entering the interactive shell.
Use -cmd Option with .quit Command
You can combine the -cmd flag with the SQLite meta‑command .quit to run a query and then terminate:
sqlite3 -cmd "select * from employees;" /opt/sqlite.db .quitUse echo or printf with Pipe
Alternatively, pipe the SQL text from echo or printf into sqlite3:
echo "select * from employees;" | sqlite3 /opt/sqlite.db
printf "select * from employees;" | sqlite3 /opt/sqlite.dbConclusion
Passing the SQL directly on the command line is the most concise method for quick queries; if issues arise, verify the sqlite3 version and environment configuration.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Ops Development & AI Practice
DevSecOps engineer sharing experiences and insights on AI, Web3, and Claude code development. Aims to help solve technical challenges, improve development efficiency, and grow through community interaction. Feel free to comment and discuss.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
