How to execute sql commands through linux shell script?

by ari.olson , in category: General Help , 7 months ago

How to execute sql commands through linux shell script?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by buster.gaylord , 7 months ago


To execute SQL commands through a Linux shell script, you can use the command-line interface of the database management system installed on your machine. Here are the general steps to follow:

  1. Install the required Database Management System (DBMS) package, such as MySQL, PostgreSQL, SQLite, etc. Ensure that the DBMS command-line tools are available in your system's PATH.
  2. Create a shell script file (.sh) using a text editor, such as vi or nano. For example, create a file named "".
  3. Add the necessary shebang line at the beginning of the script file to specify the shell to use. For example, use the following line for bash:

  1. Use the DBMS-specific command-line tool to execute SQL commands. Below are a few examples for different popular DBMS:
  • For MySQL:
mysql -u <username> -p<password> -h <hostname> -e "<SQL command>"

  • For PostgreSQL:
psql -U <username> -h <hostname> -c "<SQL command>"

  • For SQLite:
sqlite3 <database_file> "<SQL command>"

Replace <username>, <password>, <hostname>, and <database_file> with the appropriate database connection details and specify the required SQL command inside "<SQL command>".

  1. Save the shell script file and exit the text editor.
  2. Make the shell script file executable by running the following command:
chmod +x

  1. Run the script by executing the following command:

The SQL command specified in the script will be executed using the respective DBMS command-line tool, and the output or results will be displayed on the console/terminal.


by albert , 2 months ago


This is applicable for MySQL, PostgreSQL, and SQLite databases. In addition to the methods described above, it is also possible to use other CLI tools and third-party libraries to execute SQL commands. For example, you can use the 'sqlite3' command line interface for SQLite databases, 'psql' for PostgreSQL databases, and 'mysql' for MySQL databases. Make sure to install the necessary packages for your desired Database Management System.

Each DBMS tool has its own command-line options and parameters for executing SQL commands. You can refer to the respective documentation for more advanced options and functionalities.

Using this approach, you can automate SQL command execution and integrate it within your Linux shell scripts.