WP-CLI is a powerful command-line tool for managing your WordPress sites. It provides various commands to interact with WordPress, similar to how MySQL CLI allows you to manage MySQL databases. One of the useful features of WP-CLI is its ability to display results in a neatly formatted ASCII table, making it easy to read and understand.
Issue: Losing Table Formatting when Redirecting Output
When you run WP-CLI commands directly in your terminal, the results are displayed in a nicely formatted table. However, when you try to redirect the output to a file using less, tee or another program, WP-CLI detects the redirection (isPiped()) and changes the output format, often resulting in a loss of the table formatting. This can be frustrating, especially if you want to include the formatted output in an email or a text file.
Solution: Preserving ASCII Table Formatting
To keep the ASCII table formatting when redirecting WP-CLI output, you need to set the SHELL_PIPE
environment variable to 0
. This variable tells WP-CLI not to alter the output format, even when it detects redirection.
There are a few ways to set this variable:
There are a few ways to set this variable:
For the Current Terminal Session:
If you want to set the variable for the current terminal session, you can run:bash
export SHELL_PIPE=0
After running this command, all subsequent WP-CLI commands will maintain their table formatting when redirected.
Prefix Each Command: with the env var
If you prefer not to set the variable globally for the session, you can prefix each WP-CLI command with SHELL_PIPE=0
:
SHELL_PIPE=0 wp plugin list --status=active | tee wp_cli_active_plugins.txt
Programmatically in PHP or Shell Scripts (CLI or batch mode):
putenv('SHELL_PIPE=0');
$output = `wp plugin list --status=active`;
Note: the php command above using back ticks “ which execute the command and returns the generated command output.
Some server configurations disable functions such as system(), exec(), or shell_exec() and if it’s the case the command will emit a warning and return an empty or null string.
The result should look like this
How to set SHELL_PIPE environment variable globally for all users (requires Root/Admin access)
To set SHELL_PIPE=0 globally for all users and if you have root access to your server, you can add the environment variable to the /etc/profile file or another global profile script. Here are the steps to do so by editing /etc/profile with your favourite editor (vim, nano, pico) and add the following line.
export SHELL_PIPE=0