Question

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"
Était-ce utile?

La 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'"

Autres conseils

To avoid extra quoting problems you can simply wrap this in a function:

run_as_tomcat_user() {
    if [ "${USER-root}" = "root" ]
    then
        /bin/su ${TOMCAT_USER} -c "$@"
    else
        "$@"
    fi
}
run_as_tomcat_user $CATALINA_HOME/bin/catalina.sh stop 20 -force

A couple notes:

  • "${USER-root}" ensures that the code won't fail if for some reason USER is empty or even unset. Otherwise if by some coincidence the root user has run unset USER, it will still try to run with the correct user.
  • "$@" expands to every argument, properly quoted, and as such is considered a safe way to reuse parameters.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top