1

I want to run a DB2 query from shell script. I have a user db2inst1 that's required to execute DB2 statements. I am running an application that uses root user to run the shell script. HERE if I switch user to db2inst1. I can do the job.

Following is my scipt that runs perfect with db2inst1.

#!/bin/sh
db2 "connect to customerdb"
db2 "set schema = db2inst1"
db2 "insert into tbl_customer(name,occupation) values ('Alex','Admin')"

See it like a root has to run it. So root user will let the script to switch user first before executing db commands.

My app will invoke this shell script which will use root user.

How can I switch user in script? I am new to shell scripting.

1 Answer 1

1

As you are running as root, you can use:

su dbinst1 -c './your_script arg1 arg2 ...'

Were you not running as root, life would be harder.

Sign up to request clarification or add additional context in comments.

4 Comments

My app will invoke this shell script which uses root user. I want every thing to be in script. I tried: su db2inst1 -c 'db2 CONNECT TO customerdb USER db2inst1 USING admin; db2 -c -i - w -td@ -f /u01/IBM/workspace/addcustomer.sql' but I got ksh: db2: not found.
The environment is probably not set correctly; in particular, $PATH may be (re)set to a default value which does not include where the db2 command is installed. You may need to set some other environment variables too. This would be done inside the yourscript file — by whatever name you call it. Or it will be written out in a massive, multi-line command, but it is usually neater to run a script.
Adding su - dbinst1 -c with every statement in script did the job. Now my script is: su - db2inst1 -c 'db2 connect to customeradb user db2inst1 using admin' su - db2inst1 -c 'db2 -tvsf /u01/IBM/workspace/addcustomer.sql'
I am not sure why you need to be root and then use su to execute a script as another user. This makes things needlessly complex. Why not just grant access INSERT into the table to the ID that is executing script (i.e. the ID that is running the app?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.