su -c <user> command fails in shell script

18 views Asked by At

I was trying to generate a heap dump by the script below. The jmap command works from the cmd. But it fails if I run by the script. Any idea why?

#!/bin/bash

# Check to ensure we're running as root.
if [[ $EUID -ne 0 ]]; then
    echo "This script must be run as root. Either run as root or with sudo"
    exit 1
fi

source ~/.bash_profile

if pgrep -f Bootstrap; then
    product="tomcat"
    user="tomcat"
    file_path="apache-tomcat"
    process_id=$(pgrep -f Bootstrap)
else
    echo "Cannot find pid of running $product application"
    exit 1
fi

JmapPath=$(command -v jmap)
cmd="${JmapPath} -dump:format=b,file=/tmp/${product}_heapdump_$(date +%Y-%m-%d_%H-%M-%S).hprof ${process_id}"
echo $cmd
su -c '${cmd}' $user
0

There are 0 answers