Bash

Bash (Bourne Again SHell) is a Unix/Linux command-line shell and scripting language widely used for system administration, automation, and DevOps.
Bash scripts are plain text files interpreted by /bin/bash.
Create a script
Add the shebang:
Make it executable:
Run:
Commands
Bash commands are executables or shell built-ins.
Piping:
Comments
Variables
Create variable:
Use variable:
Read-only variable:
Get variable information:
Special variables
Variable
Description
$0
Script name
$1..$9
Positional arguments
$#
Number of arguments
$@
All arguments
$?
Exit code of last command
$$
Current process ID
$USER
Current user
$HOSTNAME
Host name
$PWD
Current directory
$HOME
Home directory
Arrays
Declare an array:
Access element:
Array length:
Iterate:
Associative arrays (hash tables)
Access value
Keys / values
Operators
Arithmetic operators
Comparison operators
Operator
Description
-eq
equals
-ne
not equals
-gt
greater than
-ge
greater or equal
-lt
less than
-le
less or equal
Logical operators
Operator
Description
&&
AND
||
OR
!
NOT
Condition statements
If / Else
Case (switch)
Loops
For
For each (array)
While
Do while
Write / read on console
Write to console
Without newline:
Read input
With prompt:
Hidden input (password):
Files and folder operations
Command
Description
touch file.txt
Create file
mkdir dir
Create directory
cp a b
Copy file
cp -r dir1 dir2
Copy directory
mv old new
Move / rename
rm file
Delete file
rm -r dir
Delete directory
test -f file
Check file exists
test -d dir
Check directory exists
Files I/O
File descriptors
Descriptor
Name
Description
0
stdin
Input
1
stdout
Output
2
stderr
Error output
Read line by line
Preserve whitespaces:
Write to file from script
Append to file:
Check file extension and properties
Command
Description
test -f file.txt
Check if the file exists
test -d dir
Check if the directory exists
test -r file.txt
Check if the file is readable
test -w file.txt
Check if the file is writable
test -x file.txt
Check if the file is executable
File size & content info
Pipe operators
Operator
Description
|
Send output to another command
>
Write output to file
>>
Append output to file
<
Read input from file
Named pipes (FIFOs)
Create a pipe as a file:
Write:
Read:
Pipes with loops
Preserve formatting:
Output formatting
Command
Description
grep
Filter output
awk
Column processing
sed
Stream editing
cut
Extract fields
tee
Output to file and stdout
Example:
Last updated