Introduction to Shell Scripting: Variables, Strings, Conditionals, Loops, and Execution
This article provides a beginner-friendly guide to shell scripting, covering script creation, variable definitions, read‑only and unset variables, string handling with quotes, echo usage, conditional if‑else statements, for and while loops, and two methods for executing scripts, all illustrated with clear code examples.
Shell scripting is presented as a practical way to build small automation tools such as hardware checks, one‑click web environment setup, and log analysis, making it ideal for beginners who want to write useful scripts.
Creating a shell script : Use vi test.sh to create a file, and start it with the shebang line #!/bin/bash.
Shell variables : Define a variable with a=10, print it with echo $a or echo ${a}. Read‑only variables are created with readonly your_name, and variables can be removed with unset a (note that unset cannot delete read‑only variables).
String literals : Single quotes preserve the exact characters ( str='this is a apple') and do not expand variables, while double quotes allow variable expansion ( str="this is a apple2") and support escape sequences.
Echo command : echo "\"it is a bug\"" prints "it is a bug". Use \n for a newline and \c to suppress the trailing newline.
If‑else statements :
#!/bin/bash
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
fi
if [ $a != $b ]
then
echo "a is not equal to b"
fiThe script outputs a is not equal to b. Additional forms such as if..else..fi and if..elif..fi follow the same structure.
For loop example:
for loop in 1 2 2 3
do
echo "$loop"
doneThe loop syntax is for … in …; do …; done.
While loop example:
int=1
while(($int<=5))
do
echo $int
let "int++"
doneDemonstrates a numeric condition and increment.
Executing a shell script : Either grant execute permission and run chmod +x ./hello.sh && ./hello.sh, or invoke the interpreter directly with bash hello.sh or sh hello.sh.
The article concludes with a practice exercise to write a script that calculates the factorial of 10 using the commands introduced.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
360 Quality & Efficiency
360 Quality & Efficiency focuses on seamlessly integrating quality and efficiency in R&D, sharing 360’s internal best practices with industry peers to foster collaboration among Chinese enterprises and drive greater efficiency value.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
