Basic Shell Script Variables (WECM100/b006.sh)
This page describes a basic shell script designed for embedded beginners, demonstrating the use of variables in a Linux shell environment. The script is executed within a Windows Subsystem for Linux (WSL) environment on Windows 11.
Environment
- Machine: ASUS VIVO BOOK, Bluetooth Mouse
- OS: Ubuntu using WSL on Windows 11
- Editor: VS Code on Windows 11
- Linux Kernel:
Linux asus-oda 5.15.167.4-microsoft-standard-WSL2 1 SMP Tue Nov 5 00:21:55 UTC 2024 x86_64 x86_64 x86_64 GNU/Linux
- User Home Directory:
/home/miura
- Current User:
miura
- Script Location:
./WECM100/b006.sh
Script (b006.sh)
#!/bin/bash
x=100
y="2.5"
z="0.5"
name="pizero"
price=3200
# Add ------------------
sum=$((10+10+10+10+10+10+10+10+10+10+10+10+10+10+10+10+10+10+10+10))
echo "{\"x\":$x,\"y\":$y,\"add\":$sum}"
# Increment x --------------------------
x=$((x + 100))
echo "{\"x\":$x}"
# Create Sentence ------------------
echo "$name is $price yen"
# Round ----------------------------
add=$(echo "$y + $z" | bc)
round=${add%.*}
echo "{\"y\":$y,\"round\":$round}"
y="2.4"
add=$(echo "$y + $z" | bc)
round=${add%.*}
echo "{\"y\":$y,\"round\":$round}"
Script Execution Steps
- Navigate to the script directory:
cd ./WECM100
- Edit the script:
nano b006.sh
- Make the script executable:
chmod +x b006.sh
- Execute the script:
./b006.sh
Output
{"x":100,"y":2.5,"add":200}
{"x":200}
pizero is 3200 yen
{"y":2.5,"round":3}
{"y":2.4,"round":2}
Explanation
- Variable Declaration: The script demonstrates how to declare and assign values to variables (e.g.,
x=100, name="pizero").
- Arithmetic Operations: It shows basic arithmetic operations using
$((...)) for integer calculations and bc for floating-point calculations.
- String Interpolation: The script demonstrates how to embed variable values within strings using
$variable.
- Rounding: It uses
bc to perform floating-point addition and then extracts the integer part using parameter expansion (${add%.*}).
- JSON Output: The script formats its output as JSON for easy parsing.
This script provides a simple introduction to shell scripting variables, arithmetic, and string manipulation, making it ideal for beginners working with embedded systems.