Wp plugin is-active (WP-CLI)

Uit De Vliegende Brigade
Naar navigatie springen Naar zoeken springen
$ wp help plugin is-active

NAME

  wp plugin is-active

DESCRIPTION

  Checks if a given plugin is active.

SYNOPSIS

  wp plugin is-active <plugin> [--network]

  Returns exit code 0 when active, 1 when not active.

OPTIONS

  <plugin>
    The plugin to check.

  [--network]
    If set, check if plugin is network-activated.

EXAMPLES

    # Check whether plugin is Active; exit status 0 if active, otherwise 1
    $ wp plugin is-active hello
    $ echo $?
    1

How to capture the output?

This works:

wp plugin is-installed wp-rocket; result=$(echo $?); echo "Result: >>>${result}<<<"

Some clues about what's going on:

Bash/WordPress function `wp plugin is-active wp-rocket` returns a 0 or 1.
How to capture that output in a variable?
ChatGPT
Certainly! In Bash, you can capture the output of a command using the
$(...) syntax. Here's an example of how you can capture the output of the
wp plugin is-active wp-rocket command into a variable:

bash
Copy code
# Store the output of the command in a variable
result=$(wp plugin is-active wp-rocket)

# Check the value of the variable (0 or 1)
echo "Result: $result"
This will store the output of wp plugin is-active wp-rocket (which is
either 0 or 1) into the variable result. You can then use echo, if statements,
or other operations with this variable as needed in your Bash script.

User
Are you sure? I don't get anything when I use 
`result=$(wp plugin is-active wp-rocket); echo ">>>${result}<<<"`, but I do get
meaningful output when I use `wp plugin is-active wp-rocket; echo $?`. How come?

ChatGPT
The reason why you're not getting the expected output when using 
result=$(wp plugin is-active wp-rocket); echo ">>>${result}<<<" is that the wp
command might be sending the output to the standard error stream (stderr) rather
than the standard output stream (stdout).

When you use result=$(wp plugin is-active wp-rocket), it captures only the standard
output, not the standard error. If the wp command is sending its output to stderr,
it won't be captured in the result variable.

However, when you use wp plugin is-active wp-rocket; echo $?, you're capturing the
exit status ($?), which is different from capturing the command output. In Bash,
a command's exit status (0 or 1 in this case) can be retrieved using $?. An exit
status of 0 typically indicates success, while a non-zero status indicates an error
or failure.

If you want to capture both stdout and stderr into a variable, you can use a slightly
different approach by redirecting stderr to stdout:

bash
Copy code
# Capture both stdout and stderr in the variable
result=$(wp plugin is-active wp-rocket 2>&1)

# Check the value of the variable
echo "Result: >>>${result}<<<"
The 2>&1 syntax here redirects stderr (file descriptor 2) to stdout (file descriptor 1),
so both streams are captured in the result variable. This should capture the output
you're looking for.