How to execute sql commands through linux shell script?

by ari.olson , in category: General Help , 21 days ago

How to execute sql commands through linux shell script?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by buster.gaylord , 20 days 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.