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 % operator in Bash serves three distinct syntactic roles depending on its evaluation context: an arithmetic modulo operator, a parameter expansion operator for suffix removal, and a job control specifier.

Arithmetic Modulo Operator

Within an arithmetic evaluation context, % functions as the modulo operator. It evaluates the remainder of integer division between two operands. Because Bash natively supports only integer arithmetic, floating-point operands will result in a syntax error. Syntax:
$(( dividend % divisor ))
(( dividend % divisor ))
let "var = dividend % divisor"
Mechanics:
  • Evaluated exclusively inside Bash’s internal arithmetic contexts ($(( )), (( )), or let).
  • The sign of the result matches the sign of the dividend.
  • Division by zero throws a division by 0 runtime error.
Example:
echo $(( 10 % 3 ))   # Outputs: 1
echo $(( -10 % 3 ))  # Outputs: -1

Parameter Expansion (Suffix Pattern Removal)

Within parameter expansion, % acts as a pattern-matching operator that strips a specified suffix from a variable’s string value. It uses standard shell globbing rules (not regular expressions) to match the pattern against the end of the string. Syntax:
${variable%pattern}   # Non-greedy (shortest match)
${variable%%pattern}  # Greedy (longest match)
Mechanics:
  • Single % (Non-greedy): Deletes the shortest possible match of the pattern from the right side (suffix) of the expanded $variable.
  • Double %% (Greedy): Deletes the longest possible match of the pattern from the right side of the expanded $variable.
  • If the pattern does not match the suffix, the original string is returned unmodified.
Example:
string="base.module.ext"

echo ${string%.*}   # Outputs: base.module (strips shortest match of ".*")
echo ${string%%.*}  # Outputs: base (strips longest match of ".*")

Job Control Specifier

In an interactive shell environment (or scripts where set -m is enabled), % is used as a prefix to reference background or suspended jobs by their job ID or command string, rather than their Process ID (PID). Syntax:
%        # References the current job (synonym for %% and %+)
%%       # References the current (most recently foregrounded/backgrounded) job
%+       # Same as %%
%-       # References the previous job
%n       # References job number 'n'
%string  # References the job whose command begins with 'string'
%?string # References the job whose command contains 'string'
Example:
fg %1       # Brings job 1 to the foreground
kill -15 %  # Sends SIGTERM to the current job
Master Bash with Deep Grasping Methodology!Learn More