Ask Your Question

How to capture exit code of shell command?

asked 2015-09-09 14:10:11 -0600

syphrix gravatar image

updated 2015-09-10 11:48:48 -0600

Specifically, my situation is one where I want to check if a command already exists on a system. I know how to do what I want to do in ruby using the system method which converts the shell command's return value into a boolean

if system('type my_cmd')

But how do I do something like this in puppet?

Edit for clarity:

I'm aware of the onlyif attribute in the exec resource, but I don't want to execute another shell command based on this information. I want to invoke a Puppet module, and this information will decide how I do it. Here's an example of what I'm basically trying to make my Puppet code look like

if $command_exists {
  include my_module
else {
  class { 'my_module':
    cmd_installer => 'http://path/to/command/installer'
edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted

answered 2015-09-10 16:15:01 -0600

GregLarkin gravatar image

The best way to do this is with a custom fact named "commandexists" (or whatever) that the agent presents to the master when it checks in to request a catalog. See here for more details:

Your custom fact code will simply check for the presence of the command on the agent node and set the return value to true or false.

Your code will be as you wrote it above, except I would explicitly namespace the fact variable like so:

if $::command_exists {
  include my_module
else {
  class { 'my_module':
    cmd_installer => 'http://path/to/command/installer'
edit flag offensive delete link more


Just a couple hours ago I started working on a custom fact to deal with this. Good to know that's the party line on this problem. Thanks!

syphrix gravatar imagesyphrix ( 2015-09-10 16:44:17 -0600 )edit

Glad to help, and good luck!

GregLarkin gravatar imageGregLarkin ( 2015-09-10 17:02:39 -0600 )edit

answered 2015-09-10 04:28:12 -0600

SimonH gravatar image

I'd suggest looking at the exec resource type ( and specifically the onlyif and unless options which will only run the command when certain conditions are met.

Using your example above, you could do something like

exec { 'my_command' :
    path => '/bin:/usr/bin',
    command => 'do_stuff',
    onlyif => 'type my_cmd',
edit flag offensive delete link more


I'm not looking to execute another command based on this information, though. This info is going to decide how I invoke another Puppet module. I'll be more clear in my question by adding some sudo Puppet code for what I'm really trying to accomplish.

syphrix gravatar imagesyphrix ( 2015-09-10 11:38:10 -0600 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2015-09-09 14:10:11 -0600

Seen: 1,934 times

Last updated: Sep 10 '15