Search code examples
bashinitsu

bash su with parameters in init script


In an init script I would like to call another script with a different user (in this case the catalina.sh from tomcat) and pass additional parameters.

I have tried something like this:

if [ $USER == "root" ]
then
  CMD="/bin/su ${TOMCAT_USER} -c"
fi

$CMD $CATALINA_HOME/bin/catalina.sh stop 20 -force

However, this fails as 'stop' and the other parameters are treated as a individual files and not as a parameter to the script and that files obviously don't exist. I have tried to work around that by using "$(printf())" to construct the necessary command, but haven't been able to find a working solution. Any ideas how I could pass additional parameters to that script?

Edit:

Providing more context in case the current user already is the required user. This is an ugly workaround which seems to solve the problem:

 if [ $USER == "root" ]
then
  CMD="/bin/su ${TOMCAT_USER} -c '"
  PST="'"
elif [ $USER == "${TOMCAT_USER}" ]
then
  CMD=''
  PST=''
else
  exit 1
fi

bash -c "$CMD$CATALINA_HOME/bin/catalina.sh stop 20 -force$PST"

Solution

  • Use any of these 2 ways to run a command line:

    bash -c "$CMD '$CATALINA_HOME/bin/catalina.sh stop 20 -force'"
    

    OR

    eval "$CMD '$CATALINA_HOME/bin/catalina.sh stop 20 -force'"