This article is half-done without your Comment! *** Please share your thoughts via Comment ***
As per the en.wikibooks.org:
Bash is a “Unix shell”: a command-line interface for interacting with the operating system. It has the ability to run an entire script of commands, known as a “Bash shell script”.
I recently started to create UNIX / LINUX Bash Shell script for enhancing my PostgreSQL DBA Work. You can create a Bash shell script and can connect PostgreSQL using psql.
In this post, I am sharing a sample bash shell script to execute psql commands.
Open a new file in vi editor:
1 |
[root@dbrnd anvesh]$ vi helloworld.bash |
Press [i] key to get an insert prompt:
Copy below sample Bash Shell Script and Paste into vi editor:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#!/bin/bash ################################################### # First Bash Shell script to execute psql command ################################################### #Set the value of variable database="database_name" #Execute few psql commands: #Note: you can also add -h hostname -U username in the below commands. psql -d $database -c "CREATE TABLE public.tbl_students(rno integer, name character varying)" psql -d $database -c "INSERT INTO public.tbl_students VALUES (1,'Anvesh'),(2,'Neevan'),(3,'Roy'),(4,'Martin'),(5,'Jenny')" psql -d $database -c "SELECT *FROM public.tbl_students" #Assign table count to variable TableCount=$(psql -d $database -t -c "select count(1) from public.tbl_students") #Print the value of variable echo "Total table records count....:"$TableCount |
Press [Esc] key to get a command prompt and execute below command:
To save and exit vi editor.
1 |
:wq |
Give permission to the file:
1 |
[root@dbrnd anvesh]$ chmod +x helloworld.bash |
Execute this file:
1 |
[root@dbrnd anvesh]$ ./helloworld.bash |
You can find below result:
1 2 3 4 5 6 7 8 9 10 |
rno | name -----+-------- 1 | Anvesh 5 | Jenny 2 | Neevan 3 | Roy 4 | Martin (5 rows) Total table records count....: 5 |