Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The -c (command) option instructs the Bash executable to read and execute a command string provided as the option-argument to the -c flag, rather than reading commands from standard input or a script file. Once the commands within the string are parsed and executed, the shell process terminates.
bash -c command_string [command_name] [argument...]

Argument Parsing and Positional Parameters

When Bash is invoked with -c, the assignment of positional parameters differs from standard script execution. The non-option arguments (operands) following the command_string are assigned to the shell’s internal variables starting at $0 rather than $1.
  • command_string: The option-argument containing the literal string of Bash syntax to be evaluated.
  • command_name ($0): The first non-option argument following the command string is assigned to $0. This sets the name of the shell or script for the duration of the execution, which dictates how the shell identifies itself in error messages.
  • argument... ($1, $2, etc.): Subsequent non-option arguments are assigned to the standard positional parameters.

# Syntax visualization of parameter assignment
bash -c 'echo "Context: $0, First arg: $1, Second arg: $2"' process_name arg1 arg2

Execution Mechanics

  1. Process Creation: Invoking bash -c spawns a new child Bash process.
  2. String Evaluation: The new shell evaluates the command_string exactly as if it were reading a script file. It supports the full Bash grammar, including pipelines, redirections, loops, and conditional statements.
  3. Termination: The exit status of the bash -c invocation is the exit status of the last command executed within the command_string.

Quote Interpolation and Expansion

Because the command_string is typically passed from a parent shell, the quoting mechanism used dictates whether variable expansion occurs in the parent shell or the child shell. Single Quotes (Child Shell Expansion): Prevents the parent shell from interpreting variables. The literal string is passed to the child bash process, which then performs the expansion.
bash -c 'echo $BASHPID'
Double Quotes (Parent Shell Expansion): The parent shell expands variables before passing the resulting string to the child bash process. The child shell receives a static string containing the already-evaluated values.
bash -c "echo $BASHPID"

Interaction with Other Flags

The -c operator can be combined with other Bash invocation flags (such as -x for debugging or -e for exiting on error). These flags must precede the command_string option-argument.
bash -e -x -c 'command1; command2'
Master Bash with Deep Grasping Methodology!Learn More