Tuesday, November 5, 2024

Shell Scripting With PHP: A Beginner’s Guide

What is Shell Scripting?

Shell scripting refers to scripting in command-line interpreters or shells. With it, we automate routine tasks, making processes efficient.

Why Use PHP for Shell Scripting?

PHP, commonly associated with web development, also shines in CLI (Command Line Interface). PHP scripts aren’t just limited to browsers.

Advantages of Using PHP for Shell Scripting:

  • Familiar Syntax: If you’re a web developer, the PHP syntax will be intuitive.
  • Cross-platform: PHP runs on Windows, MacOS, and Linux.
  • Rich Library: PHP has extensive built-in functions to aid scripting.

Getting Started With PHP CLI

To kick off, ensure you’ve PHP installed on your system. Use your terminal and type:

php -v

This simple command checks the PHP version. If you see version details, you’re set.

Writing Your First PHP Shell Script

Create a new PHP file, naming it hello.php:

#!/usr/bin/php
<?php
echo "Hello, Shell Scripting with PHP!";
?>

Here, the #!/usr/bin/php is called a shebang. It directs the script to the PHP interpreter.

Making Your Script Executable:

On Linux or MacOS, open the terminal and navigate to your script’s directory. Run the command:

chmod +x hello.php

This grants execution permissions.

Running Your Script:

Execute the script using the following command:

./hello.php

Expect “Hello, Shell Scripting with PHP!” printed on your terminal.

Basic PHP Shell Scripting Commands

1. Reading Input

Use fgets(STDIN) to read user input:

#!/usr/bin/php
<?php
echo "What's your name?";
$name = trim(fgets(STDIN));
echo "Hello, $name!";
?>

2. Command Line Arguments

PHP scripts can accept command line arguments. Access them via $argv array:

#!/usr/bin/php
<?php
if (isset($argv[1])) {
    echo "Hello, $argv[1]!";
} else {
    echo "Hello, Stranger!";
}
?>

Run it: ./scriptname.php YourName

3. Executing Shell Commands

Use shell_exec() to run shell commands within PHP:

#!/usr/bin/php
<?php
$output = shell_exec('ls');
echo $output;
?>

This script lists directory files.


PHP isn’t just a web-centric language. With its CLI capabilities, PHP extends its power to automate and script tasks. Embracing PHP for shell scripting offers the simplicity of PHP and the power of shell combined.

Related Articles

Related Articles

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles

11 easy steps in growing watermelon in a container.