Home > Back-end >  What is the meaning of `exec sh -c`
What is the meaning of `exec sh -c`

Time:12-27

I have a script draft.sh with the following format:

#!/bin/bash

set -ex

some_var=''

while getopts 'k' flag; do

  case "${flag}" in 
    k) some_var='true' ;;
    *) ;;
  esac

done

if [ -n $some_var ]; then

exec sh -c "some_command"

fi

(  echo "some other command" )| tee output.txt 

I noticed if I run ./draft.sh -k, it will run the some_command, and will not proceed to echo "some other command" ) | tee output.txt . I wonder what is the meaning of exec sh -c in this case.

CodePudding user response:

It means to change the current process you are running the shell script in to become a process that executes a new shell sh and this new shell will execute "some_command". As the process changes, there would be no continuation of the shell script you are running.

In bash, exec is a builtin. Check man builtins:

   exec [-cl] [-a name] [command [arguments]]
          If  command  is specified, it replaces the shell.  No new process is created.  The arguments become the arguments to command.  If the -l option is supplied, the shell places a dash at the beginning of the zeroth argument passed to command.  This is what login(1)
          does.  The -c option causes command to be executed with an empty environment.  If -a is supplied, the shell passes name as the zeroth argument to the executed command.  If command cannot be executed for some reason, a  non-interactive  shell  exits,  unless  the
          execfail shell option is enabled.  In that case, it returns failure.  An interactive shell returns failure if the file cannot be executed.  If command is not specified, any redirections take effect in the current shell, and the return status is 0.  If there is a
          redirection error, the return status is 1.
  • Related