About Shell Scripts

A shell (or shell interpreter) is a command interpreter. The shell interprets text strings and performs some function for each string. As part of interpreting the string, the shell may do variable or wildcard replacement or change the string in some way. Typically, the shell itself performs functions specified by internal commands and spawns a child process to perform processing on the external commands. Depending on the command, the shell then does one of the following:

A shell script is a text file whose format defines the following:

The format of a shell script, starting on line one and column one, is as follows:

   #!interpreter_path <options>
   text to be interpreted
   text to be interpreted
    .
    .
    .

where

interpreter_path is the shell interpreter.

options are the options to pass to the shell interpreter.

The spawn() and spawnp() functions support shell scripts. i5/OS currently provides the Qshell Interpreter. The Qshell Interpreter is a standard command interpreter for i5/OS based on the POSIX 1003.2 standard and X/Open CAE Specification for Shell and Utilities.

Examples

See Code disclaimer information for information pertaining to code examples.

The following is an example of using spawn() to run a shell script written for the Qshell Interpreter:

#include <stdio.h>
#include <spawn.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int argc, char *argv[])
{
   int fd_map[3], stdoutFds[2];
   char *xmp_argv[4], *xmp_envp[3];
   struct inheritance xmp_inherit = {0};
   char buffer[20];
   pid_t child_pid, wait_rv;
   int wait_stat_loc, rc;

   xmp_argv[0] = "/home/myuserid/myscript";
   xmp_argv[1] = "Hello";
   xmp_argv[2] = "world!";
   xmp_argv[3] = NULL;

   xmp_envp[0] =
       "NLSPATH=/QIBM/ProdData/OS400/Shell/MRI2924/%N";
   xmp_envp[1] = "QIBM_USE_DESCRIPTOR_STDIO=Y";
   xmp_envp[2] = NULL;

   if (pipe(stdoutFds) != 0) {
       printf("failure on pipe\n");
       return 1;
   }

   fd_map[0] = stdoutFds[1];
   fd_map[1] = stdoutFds[1];
   fd_map[2] = stdoutFds[1];

   if ((child_pid = spawn("/home/myuserid/myscript", 3,
                          fd_map, &xmp_inherit, xmp_argv,
                          xmp_envp)) == -1) {
       printf("failure on spawn\n");
       return 1;
   }

   if ((wait_rv = waitpid(child_pid,
                           &wait_stat_loc, 0)) == -1) {
       printf("failure on waitpid\n");
       return 1;
   }
   close(stdoutFds[1]);

   while ((rc = read(stdoutFds[0],
                buffer, sizeof(buffer))) > 0) {
       buffer[rc] = '\0';
       printf("%s", buffer);
   }
   close(stdoutFds[0]);
   return 0;
}

where "/home/myuserid/myscript" could look like the following:

   #!/usr/bin/qsh
   print $1 $2
Example Output:
   Hello world!


Top | Process-Related APIs | APIs by category