Sunday, 31 July 2016

Shell scripts and parameters


I recently had the problem where a shell script had to be started as root but needed a different user user1 to invoke the commands as that user alone had the correct permissions to perform the tasks.

Parameters were referenced within the script from an external entity, and using
          su user1 
              or
        su - user1
left the build in a perpetual loop as this set up the environment but waited for further commands which it didn't read from the script after the above commands.

My first idea was to create a secondary script which was implemented as user1 using the following command;
         su - user1 -c "/tmp/place1/place2/user1.sh"
but the problem this caused was that I needed to pass "secondary" parameters into this script. So the parameters for the second user script were defined externally from the first script.

I set my friend Dave the task of passing in parameters which he boldly took on;
   https://portal2portal.blogspot.co.uk/2016/07/scripting-shell.html

This would have worked and indeed was a viable option, but would have meant lots of hassle to implement. It would have looked something like this;
   initial.sh
         su - user1 -c "/tmp/place1/place2/user1.sh  \"$externalParameter1\""
   user1.sh
        mqsistart $1

But since my original script had 5 parameters being passed in multiple times, it seemed like a lot of hard work, this also didn't resolve the "perpetual loop" problem either. Instead I went for the much uglier but simpler method of having the singular shell script running commands in the following way;
    initial.sh
     su - user1 -c "mqsistart \"externalParameter1\""
     su - user1 -c "mqsichangebroker  \"externalParameter1\" -a \"externalParameter2\""

All now seems to be working. But questions for the wider world would be;
1. how could i escape the "perpetual loop"?
2. what is the best way to pass on parameters from an external source through a script to a second?