0

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
Zhang
  • 39
  • 1
  • 6
  • Variables are expanded inside double quotes, not inside single quotes. – Barmar Oct 06 '22 at 00:18
  • @Barmar I tried both actually.. Double quotes don't work either.. – Zhang Oct 06 '22 at 00:25
  • What error do you get when you use double quotes? – Barmar Oct 06 '22 at 00:27
  • @Barmar No error.. Looks like sudo is the trick. Use sudo -u -c ".." – Zhang Oct 06 '22 at 00:33
  • `sudo` shouldn't be necessary since you're already running as root. – Barmar Oct 06 '22 at 00:35
  • You say "it fails". If you're not getting an error, what is it doing wrong? – Barmar Oct 06 '22 at 00:36
  • @Barmar It did not generate the heap dump file somehow without error. – Zhang Oct 06 '22 at 00:39
  • I think you have the arguments to `su` in the wrong order -- try `su "$user" -c "${cmd}"` (or `sudo -u "$user" $cmd`, but in that form I'd recommend not building the command in a variable; see [BashFAQ #50](http://mywiki.wooledge.org/BashFAQ/050)). Also, to debug, don't use `echo`; instead, use `set -x` to turn on execution tracing and get the shell's-eye-view of what's happening as the script runs. – Gordon Davisson Oct 06 '22 at 00:48
  • @GordonDavisson I tried su "$user" -c "${cmd}" and it still didn't work. Below is the tracing. It looks correct. not sure why the dump was not generated... + su tomcat -c '/usr/bin/jmap -dump:format=b,file=/tmp/tomcat_heapdump_2022-10-06_04-43-56.hprof 6689' – Zhang Oct 06 '22 at 04:45
  • @GordonDavisson On the other hand, ```sudo -u "$user" bash -c "${cmd}"``` worked. I see the dump was generated. But still didn't understand why su failed. – Zhang Oct 06 '22 at 04:51

0 Answers0