Skip to main content

Bash Operators


Process Management Operators

SymbolMeaningExample
&Run in backgroundsleep 10 &
&&Run next only if previous succeedsmkdir newdir && cd newdir
;Run multiple commands sequentiallyecho "Hello"; echo "World"
()Run in a subshell (isolated environment)(cd /tmp; ls)
{}Group commands in current shell{ cd /tmp; ls; }
|Pipe output of one command into another`ls -l

Variable & Expansion Operators

SymbolMeaningExample
$VARExpands variableecho $HOME
$$PID of current shellecho $$
$!PID of last background processsleep 60 & echo $!
$?Exit status of last commandls /bad && echo $?
$0Script nameecho $0
$1, $2, ...Positional arguments./script.sh arg1$1 = arg1
$#Number of args passedecho $#
$@All args as separate stringsfor arg in "$@"; do echo $arg; done
$*All args as one stringecho "$*"
${VAR}Explicit expansionecho "Path: ${HOME}/bin"
${VAR:-default}Use default if unsetecho ${NAME:-Guest}

Input / Output Redirection

SymbolMeaningExample
>Redirect stdout (overwrite)echo "Hi" > file.txt
>>Redirect stdout (append)echo "More" >> file.txt
<Read from filewc -l < file.txt
2>Redirect stderrls /bad 2> error.log
&>Redirect stdout + stderrmycmd &> all.log
`>`Overwrite even with noclobber
teeOutput to file and stdout`echo "Log"

String & Pattern Matching

SymbolMeaningExample
*Match any number of charactersls *.txt
?Match one characterls file?.txt
[...]Match any in setls file[123].txt
[^...]Match any NOT in setls file[^123].txt
{A,B}Expand to A, Becho {red,blue}.jpg
{1..5}Expand numeric sequenceecho file{1..5}.txt

Command Substitution

SyntaxMeaningExample
`command`Replace with command outputecho `date`
$(command)Same, supports nestingecho $(date)

Quotes & Escaping

SymbolMeaningExample
'...'Strong quote, no expansionecho '$HOME'
"..."Weak quote, allows expansionecho "$HOME"
\Escape characterecho \"Hello\"
\nNewline (used with echo -e)echo -e "Hi\nThere"

Special Built-in Commands

SymbolMeaningExample
:No-op (does nothing): && echo "Continues"
trueAlways succeedstrue && echo "Success"
falseAlways fails`false
exitExit shell with statusexit 1
execReplace shell with commandexec ls
sourceRun script in current shellsource ~/.bashrc

Loops & Conditionals

SyntaxMeaningExample
if ... then ... fiConditional blockif [ -f file ]; then echo "Yes"; fi
[ ... ]Basic test[ -d /home ] && echo "Exists"
[[ ... ]]Extended test[[ "x" == "x" ]] && echo "Match"
for ... in ...Loop over listfor i in {1..3}; do echo $i; done
while ...Loop while conditionwhile true; do echo "Hi"; sleep 1; done

Background & Job Control

SymbolMeaningExample
&Run in backgroundsleep 10 &
jobsList background jobsjobs
fgResume job in foregroundfg %1
bgResume job in backgroundbg %1
nohupRun after logoutnohup script.sh &
disownRemove from job tabledisown %1

TL;DR: Essential Symbols

✔ Process control:     &, &&, ||, ()
✔ Variables: $, $$, $!, $@
✔ Redirection: >, <, 2>, |
✔ Patterns: *, ?, {}
✔ Quoting: '...', "...", \
✔ Job control: jobs, fg, bg, disown