Shell Scripting
Variables & Loops
Let's write a simple script to automate creating a new ESP32 project folder. This will introduce variables, user input, and conditionals.
Your First Script
Create a new file named create_project.sh and add the following code:
#!/bin/bash
# 1. Variables
# Note: DO NOT put spaces around the equals sign!
PROJECT_DIR="my_esp_projects"
# 2. Print to screen
echo "Starting project setup..."
# 3. Create the directory
mkdir -p $PROJECT_DIR
# 4. Navigate into it
cd $PROJECT_DIR
echo "Done! You are now in $PROJECT_DIR."
Making it Executable
Before you can run it, you must give the file execute permissions:
chmod +x create_project.sh
Now, run it:
./create_project.sh
(We use ./ to tell the shell "run the file that is located right here in the current directory").
Taking User Input
Scripts are more powerful when they are interactive. We use the read command to pause the script and wait for the user to type something.
#!/bin/bash
echo "What is the name of your new project?"
read PROJECT_NAME
echo "Creating folder for $PROJECT_NAME..."
mkdir -p $PROJECT_NAME
Conditionals (if statements)
Sometimes you only want to execute a command if a certain condition is met. For example, check if a file already exists before trying to download it.
#!/bin/bash
FILE="esp-idf-v5.1.zip"
# -f checks if the file exists
if [ -f "$FILE" ]; then
echo "$FILE already exists. Skipping download."
else
echo "Downloading $FILE..."
# wget https://...
fi
(Notice the spaces inside the [ ] brackets. They are strictly required in Bash!)
Loops
If you need to perform the same action on multiple files, use a for loop.
#!/bin/bash
# Loop over three specific chip names
for CHIP in esp32 esp32s2 esp32s3
do
echo "Compiling firmware for target: $CHIP"
# idf.py set-target $CHIP
# idf.py build
done
Looping Over Files
You can also loop over all files matching a pattern in a directory:
#!/bin/bash
# Find all .txt files and rename them to .log
for file in *.txt
do
mv "$file" "${file%.txt}.log"
done
You now have the foundation to read and understand the setup scripts often provided with embedded SDKs!

