Groovy process not working with linux shell (grep and awk and ps)
The shell -c
option expects one parameter only. Try this from the command line, and you'll see it fails as well:
sh -c ps -ef | sh -c grep sleep.sh | sh -c grep -v grep | sh -c awk sleep.sh
It needs quotes to work properly:
sh -c "ps -ef" | sh -c "grep sleep.sh" | sh -c "grep -v grep" | sh -c "awk sleep.sh"
You can quote the commands properly by starting with a list of strings instead of a string: proc1 = ['sh', '-c', 'ps -ef']
. In this case you're doing the filtering in groovy, so the simple solution is to simply not invoke the commands through the shell. Try this:
Process proc1 ='ps -ef'.execute()
Process proc2 ='grep sleep.sh '.execute()
Process proc3 ='grep -v grep '.execute()
Process proc4 ='awk sleep.sh '.execute()
Process all = proc1 | proc2 | proc3 | proc4
println all.text
Finally, if things don't work properly, it can be helpful to read the stderr stream with
println all.err.text
Executing long command with groovy on linux shell?
It's kinda a duplicate of the 2 questions in the comments, (plus some others I can't find at the moment), but try:
def cmd = /ps aux | grep 'unit 1' | grep -v grep | awk '{print $2}'/
def out = [ '/bin/sh', '-c', cmd ].execute().text.trim()
println out
Using groovy, how do you pipe multiple shell commands?
This works for me :
def p = 'ps aux'.execute() | 'grep foo'.execute() | ['awk', '{ print $1 }'].execute()
p.waitFor()
println p.text
for an unknown reason, the parameters of awk can't be send with only one string (i don't know why! maybe bash is quoting something differently). If you dump with your command the error stream, you'll see error relative to the compilation of the awk script.
Edit : In fact,
"-string-".execute()
delegate toRuntime.getRuntime().exec(-string-)
- It's bash job to handle arguments containing spaces with ' or ". Runtime.exec or the OS are not aware of the quotes
- Executing
"grep ' foo'".execute()
execute the command grep, with'
as the first parameters, andfoo'
as the second one : it's not valid. the same for awk
Can I use wild cards when executing a shell process in a different working directory?
this version works for me, just try it out:
#!/usr/bin/env groovy
command = ["sh", "-c", "cp -f *.php /tmp/"]
def cpProc = command.execute(null, new File('./php/'))
cpProc.waitFor()
print 'current exitvalue :' + cpProc.exitValue() + '\n'
print 'current proc out : ' + cpProc.text + '\n'
print 'ls -la'.execute(null, new File('/tmp/')).text
The first answer on this question explains why your version did not work: Groovy execute "cp *" shell command
export command not working in Jenkins groovy
Refer the below to run shell and capture the output to a variable inside a Jenkins groovy file:-
vara = sh (script: 'shell script need to be executed', returnStdout: true)
You can try something like this:-
steps {
script {
vara = sh (script: '''shell command''', returnStdout: true)
echo " The value of variable id ${vara}"
}
}
Getting PID for a process using Groovy
An alternative (as the output from ps
shouldn't block any buffers)
Integer getPid(processName) {
'ps -A'.execute()
.text
.split('\n')
.find { it.contains processName }?.split()?.first() as Integer
}
println getPid('groovyconsole')
Bash command, dates and math in Groovy
If you did want to do this with built-in stuff (as mentioned in your comment) then all you need is the start instant, the end instant and a Duration.
import java.time.*
LocalDateTime start = LocalDateTime.now()
// Do some stuff
LocalDateTime end = LocalDateTime.now()
Duration d = Duration.between(start, end)
println "Operation took ${d.seconds}.${d.nanos}s"
But I'm afraid no amount of Java's DateTime classes are going to fix your HTTP 500 error.
right syntax using command sh in jenkinsfile
Finally, I found this way and works fine:
sh """#!/bin/bash
docker images | grep 643975c526cf | awk '{print $1 ":" $2}' | sort -u | xargs docker rmi -f
"""
Shell script to capture Process ID and kill it if exist
Actually the easiest way to do that would be to pass kill arguments like below:
ps -ef | grep your_process_name | grep -v grep | awk '{print $2}' | xargs kill
Hope it helps.
Related Topics
Ansible Inside Script Command Not Found
Count the Number of Executable Files in Bash
Issue While Validating Bash Script
How to Setup the Passwords-Less Authentication Between Two Different Accounts
Multiple Ip Addresses on Google Cloud Compute
Bash - Find Files Older Than X Minutes and Move Them
Counting Number of Lines in a File Using Grep and Wc
How to Grep One String Occuring Multiple Times from Same File
Linux Script Extract Information from Excel to Create Users
Get Started with Latex on Linux
How to Write Multiple Line String Using Bash with Variables
Force Unmount of Nfs-Mounted Directory
How to Gzip All Files in All Sub-Directories into One Compressed File in Bash
How to Format My Grep Output to Show Line Numbers at the End of the Line, and Also the Hit Count
How to Check If a Service That I Don't Know the Name of Is Running on Ubuntu