Search code examples
basharithmetic-expressions

How nest ancillary command in bash arithmetic command


I want to print the uptime for a jvm which is running on my machine. I can do that using jcmd. However I want to print it out in minutes. So, I tried the following:

bash-3.2$echo $(($(jcmd 785 VM.uptime)/60))

However this isn't working. I get the following error:

bash-3.2$ echo $(($(jcmd 785 VM.uptime)/60))
bash: 785:
1541.343 s/60: syntax error in expression (error token is ":
1541.343 s/60")

If I assign $(jcmd 785 VM.uptime) to a variable first and substitute that into the arithmetic expression, it still doesn't work. Any idea how I can get this to work?


Solution

  • Your output is not an integer, and has a character 's'. You should cut unnecessary part:

    echo $(( $(jcmd 785 VM.uptime |sed 's/^\([[:digit:]]*\).*$/\1/')/60 ))
    

    or

    echo "scale=4;$(jcmd 785 VM.uptime |sed 's/ s//')/60" |bc
    

    -- this will give you a float value.