</>
Skip to content
Bash lessons (4/29)

Bash — Syntax

Variables

#!/bin/bash

# Assign variable (no spaces!)
name="Alice"
age=30

# Use variable
echo "Name: $name"
echo "Age: ${age}"

# Read input
read -p "Enter name: " username
echo "Hello, $username!"

Command substitution

#!/bin/bash

# Use $(command) to capture output
today=$(date +%Y-%m-%d)
files=$(ls | wc -l)

echo "Today: $today"
echo "Files: $files"

Arithmetic

#!/bin/bash

a=10
b=3

echo "Add: $((a + b))"
echo "Sub: $((a - b))"
echo "Mul: $((a * b))"
echo "Div: $((a / b))"
echo "Mod: $((a % b))"

Special variables

#!/bin/bash

echo "Script name: $0"
echo "First arg: $1"
echo "Second arg: $2"
echo "All args: $@"
echo "Number of args: $#"
echo "Exit status: $?"

String operations

#!/bin/bash

s="Hello, World!"

echo "Length: ${#s}"           # 13
echo "Substring: ${s:0:5}"    # Hello
echo "Replace: ${s/World/Bash}" # Hello, Bash!
echo "Uppercase: ${s^^}"      # HELLO, WORLD!
echo "Lowercase: ${s,,}"      # hello, world!

Mini Practice

Write Bash code that:

  1. Declares and uses variables
  2. Uses command substitution
  3. Performs arithmetic operations
  4. Manipulates strings

Up Next

In the next lesson, you'll learn about Comments — documenting your scripts.

Related Topics

Frequently Asked Questions about Syntax

What is Syntax in Bash?

Syntax is a fundamental concept in Bash. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Syntax?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Syntax.

Why is Syntax important in Bash?

Syntax is essential for Bash development. Understanding this concept will help you write better code and solve real-world problems more effectively.