Variables
6 snippetsAssign
name="John"Use
echo $name
echo ${name}Read Input
read -p "Enter name: " nameArray
fruits=("apple" "banana" "cherry")Array Access
echo ${fruits[0]}
echo ${fruits[@]}Length
echo ${#name} # String length
echo ${#fruits[@]} # Array lengthControl Flow
5 snippetsIf/Else
if [ $x -gt 0 ]; then
echo "positive"
elif [ $x -lt 0 ]; then
echo "negative"
else
echo "zero"
fiFor Loop
for i in 1 2 3 4 5; do
echo $i
doneFor Range
for i in {1..5}; do
echo $i
doneWhile Loop
while [ $count -lt 10 ]; do
((count++))
doneCase
case $day in
"Mon") echo "Monday" ;;
"Tue") echo "Tuesday" ;;
*) echo "Other" ;;
esacComparisons
3 snippetsNumbers
-eq # Equal
-ne # Not equal
-gt # Greater than
-lt # Less than
-ge # Greater or equal
-le # Less or equalStrings
= # Equal
!= # Not equal
-z # Empty
-n # Not emptyFiles
-f # Is file
-d # Is directory
-e # Exists
-r # Readable
-w # Writable
-x # ExecutableTired of looking up syntax?
DocuWriter.ai generates documentation and explains code using AI.
Functions
4 snippetsFunction
greet() {
echo "Hello, $1!"
}Call
greet "World"Return Value
add() {
echo $(($1 + $2))
}
result=$(add 5 3)Local Variable
myfunc() {
local name="John"
}String Operations
5 snippetsConcatenate
full="$first $last"Substring
echo ${name:0:5} # First 5 charsReplace
echo ${name/old/new} # First occurrence
echo ${name//old/new} # All occurrencesUppercase
echo ${name^^}Lowercase
echo ${name,,}File Operations
4 snippetsRead File
cat file.txt
while read line; do
echo "$line"
done < file.txtWrite File
echo "text" > file.txt # Overwrite
echo "text" >> file.txt # AppendCheck File
if [ -f "file.txt" ]; then
echo "File exists"
fiLoop Files
for file in *.txt; do
echo "$file"
doneCommon Commands
4 snippetsPipe
cat file.txt | grep "pattern"Redirect
command > output.txt 2>&1Command Sub
today=$(date +%Y-%m-%d)Exit Status
if [ $? -eq 0 ]; then
echo "Success"
fi