Sunday 31 July 2016

Scripting the shell

One of my friends was looking for a mechanism to invoke a script as another user AND pass in a parameter.

Challenge, accepted :-)

Here's my script: -

/home/db2inst1/foobar.sh 

#!/bin/bash
echo "Hello World! from `whoami`"
echo "And today's special is " $1 "!!! "
exit


and here's how I invoke it from another user ( root ): -

su - db2inst1 -c '/home/db2inst1/foobar.sh Fish'

Hello World! from db2inst1
And today's special is  Fish !!! 

su - db2inst1 -c "/home/db2inst1/foobar.sh Beef"

Hello World! from db2inst1
And today's special is  Beef !!! 


Bottom line, wrap the remote command in single or double quotes, with the parameter passed after the name of the script.

3 comments:

Aiden Gallagher said...

Challenge Accepted and Challenge Completed. Sort of.

It's my own fault for not giving you the full picture, but this works for definite. But works sequentially(or so i believe). So;

#!/bin/bash
echo "Hello World! from `whoami`"
echo "And today's special is " $1 "!!! and tomorrows special is " $2 "!!"
exit


su - db2inst1 -c '/home/db2inst1/foobar.sh Fish Beef'

Hello World! from db2inst1
And today's special is Fish !!! and tomorrows special is Beef !!


BUT say the parameters were passed into the first script initially. so the first script itself was referencing $todaysSpecial, and also $tomorrowsSpecial, $lastWeeksSpecial $lastYearsMostOrderedDish.

Now if the second script read these sequentially(as i understand this method is) would this be done in the following way?
#!/bin/bash
echo "Hello World! from `whoami`"
echo "And today's special is " $1 "!!! and tomorrows special is " $2 "!! last weeks special was $3 and last years most ordered dish was $4"
exit


su - db2inst1 -c '/home/db2inst1/foobar.sh "$todaysSpecial" "$tomorrowsSpecial" "$lastWeeksSpecial" "$lastYearsMostOrderedDish" !!!'

Then... Say you wanted to reference the same parameter twice in the second script would you keep calling $1 or $2 every time you wanted these values?

...The plot thickens

Dave Hay said...

Aiden

Hmmm, OK, so I'd go back to first principles, and ask "What's the actual requirement?".

Sometimes it helps to remember that your objective was to drain the swamp, when you're standing up to your waist in alligators :-)

Cheers, Dave

Aiden Gallagher said...

Alas, my full requirements and eventual answer can be found here;
http://aidensgallyvanting.blogspot.co.uk/2016/07/shell-scripts-and-parameters.html
leave a comment if you have any of the answers

Aiden

Visual Studio Code - Wow 🙀

Why did I not know that I can merely hit [cmd] [p]  to bring up a search box allowing me to search my project e.g. a repo cloned from GitHub...