Description: This script demonstrates basic printf usage in a shell script, executed within a WSL (Windows Subsystem for Linux) environment on Windows 11. It's designed for beginners to understand how to format and output data in JSON-like structures.
Machine: ASUS VivoBook, Bluetooth Mouse
OS: Ubuntu using WSL on Windows 11
Editor: VS Code
$ uname -a:
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
$ pwd > /home/miura
$ whoami > miura
$ cd ./WECM100
$ nano b003.sh ## Edit shell script
$ chmod +x b003.sh
$ ./b003.sh
#!/bin/bash
codeId="WECM100"
x=10
y=20
printf '{"codeId":"%s"}\n' $codeId
printf '{"x":%d}\n' $x
printf '{"y":%d}\n' $y
printf "{\"codeId\":\"%s\"}\n" $codeId
printf "{\"x\":%d}\n" $x
printf "{\"y\":%d}\n" $y
printf "{\"x\":0x%02X}\n" $x
printf "{\"y\":0x%02X}\n" $y
{"codeId":"WECM100"}
{"x":10}
{"y":20}
{"codeId":"WECM100"}
{"x":10}
{"y":20}
{"x":0x0A}
{"y":0x14}
The script uses printf to format and output data. Here's a breakdown:
codeId="WECM100", x=10, y=20: These lines initialize variables.printf '{"codeId":"%s"}\n' $codeId: This prints the codeId variable as a JSON-like string. %s is a string format specifier.printf '{"x":%d}\n' $x: This prints the x variable as an integer. %d is an integer format specifier.printf "{\"x\":0x%02X}\n" $x: This prints the x variable in hexadecimal format. %02X formats the integer as a two-digit uppercase hexadecimal number with leading zeros if needed.This script is a simple introduction to printf and variable usage in shell scripting, which is essential for embedded development and system administration.