How to call Shell Script from Perl code example

Multiple ways to call a shell script or a command from Perl code.

  • Using System function with command and arguments, example system(“sh test.sh”,), control returned to called code with output and errors.
  • using the exec function, It breaks the execution once the command executes.

How to call shell commands or scripts from Perl with code examples

  • using the System function

The System function executes the command or scripts and returns the control to the next line of execution Syntax:

system(commands,arguments)
  • Commands are shell commands.
  • arguments are parameters passed to commands

For example, a System command executes shell commands, and It executes the command and control returned to the next line. And it prints the string

system("ls -l"); ## or you can use system("ls" , "-l");

print "End\n";

Output:

total 4
-rw-rw-r-- 1 sbx_user1051 990 66 Dec 20 14:21 main.plx
-rw-rw-r-- 1 sbx_user1051 990 0 Dec 20 14:21 stdin
End

TO execute the shell script file from a Perl code

system("sh","test.sh"); ## or you can use system("ls" , "-l");

print "End\n";

It executes the command sh test.sh and returns the output and control to the next line.

You can also check conditional expressions to evaluate script is executed or not

my @status=system("sh","test.sh"); ## or you can use system("ls" , "-l");

# Check the status
if ($status == 0) {
    print "Script executed \n";
} else {
    print "Failed to execute script with exit code: $status\n";
}

system returns the exit code of a script execution. 0 tells successful, Other numbers tell failure to execute.

  • using the exec function

The exec function executes the command or scripts and does not return the control, or stop its execution. Syntax:

exec(commands,arguments)
  • Commands are shell commands.
  • arguments are parameters passed to commands

For example, exec command to execute shell commands, executes the command and stops its execution after the command executes, And it does not print the string.

exec("ls -l"); ## or you can use exec("ls" , "-l");

print "End\n";

Output:

total 4
-rw-rw-r-- 1 sbx_user1051 990 66 Dec 20 14:21 main.plx
-rw-rw-r-- 1 sbx_user1051 990 0 Dec 20 14:21 stdin

TO execute the shell script file from a Perl code using the exec command

exec("sh","test.sh");

print "End\n";

It executes the command sh test.sh and control does not go to the next line.

Conclusion

Multiple ways to execute shell commands from Perl code, The System executes scripts or commands and returns the control to the next line. The exec function also does the same but does not return to the next code statement. Please be aware executing scripts with these approaches has security concerns.