SH

Bash Cheatsheet

Bash shell scripting reference - variables, conditionals, loops, and the file/text commands used constantly.

Variables & basics

x="value"

Set a variable (no spaces around =)

echo $x

Print a variable's value

$1, $2, ...

Positional script arguments

$#

Number of arguments passed

$?

Exit code of the last command

Conditionals & loops

if [ "$x" = "y" ]; then ...; fi

If statement

for i in 1 2 3; do ...; done

For loop

while [ condition ]; do ...; done

While loop

[ -f file ]

Test if a file exists

[ -d dir ]

Test if a directory exists

Common commands

ls -la

List files, including hidden, with details

grep "pattern" file

Search text in a file

find . -name "*.js"

Find files by name pattern

chmod +x file

Make a file executable

cat file | grep x | wc -l

Pipe commands together