@ari.olson
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:
- 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.
- Create a shell script file (.sh) using a text editor, such as vi or nano. For example, create a file named "execute_sql.sh".
- 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:
- Use the DBMS-specific command-line tool to execute SQL commands. Below are a few examples for different popular DBMS:
1
|
mysql -u <username> -p<password> -h <hostname> -e "<SQL command>"
|
1
|
psql -U <username> -h <hostname> -c "<SQL command>"
|
1
|
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>"
.
- Save the shell script file and exit the text editor.
- Make the shell script file executable by running the following command:
1
|
chmod +x execute_sql.sh
|
- 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.