Introduction
In this project, you will learn how to create a chess board using Bash scripting. By completing this project, you will gain experience in using nested loops, color printing, and shell scripting.
🎯 Tasks
In this project, you will learn:
- How to set up the environment for creating the chess board
- How to prompt the user for the size of the chess board
- How to use nested loops to print the chess board with alternating black and white cells
🏆 Achievements
After completing this project, you will be able to:
- Create a visual chess board using Bash scripting
- Utilize nested loops to generate a grid-like structure
- Implement color printing to enhance the visual appeal of the output
- Prompt the user for input and use that input to generate the desired output
Set up the Environment
In this step, you will set up the environment for creating the chess board.
- Open a text editor and create a new file named
chessBoard.sh. - Add the following shebang line at the beginning of the file:
#!/bin/bash
This line tells the system to use the Bash shell to execute the script.
Prompt the User for the Board Size
In this step, you will prompt the user to enter the size of the chess board.
- Add the following code to your script:
echo -e "\e[44m[Input]\e[0m Enter the size of the chess board: "
read value
This code will display a prompt for the user to enter the size of the chess board, and store the user's input in the value variable.
Print the Chess Board
In this step, you will use nested loops to print the chess board.
- Add the following code to your script:
echo -e "\n\n\e[42m[OUTPUT]\e[0m REQUESTED CHESS-BOARD \e[42m[OUTPUT]\e[0m"
for ((row = 1; row <= value; row++)); do
for ((col = 1; col <= value; col++)); do
sumOfRowAndCol=$(($(($row + $col)) % 2))
if [ $sumOfRowAndCol -eq 0 ]; then
echo -e -n "\033[47m" " "
else
echo -e -n "\033[40m" " "
fi
done
echo -ne "\033[0m" " "
echo
done
echo -n -e "\033[0m"
This code uses nested loops to iterate through the rows and columns of the chess board. For each cell, it calculates the sum of the row and column indices, and uses this value to determine whether the cell should be black or white. The echo commands are used to print the appropriate color for each cell, and to reset the color after each row.
Run the Script
In this step, you will run the script to generate the chess board.
- Save the
chessBoard.shfile. - Open a terminal and navigate to the directory where you saved the script.
- Make the script executable by running the following command:
chmod +x chessBoard.sh
- Run the script by executing the following command:
./chessBoard.sh
The script will prompt you to enter the size of the chess board, and then it will print the chess board to the terminal.
Congratulations! You have successfully created a chess board using Bash scripting.
Summary
Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.



