Beginner-Friendly Guide to Linux Shell Programming
This article provides a step‑by‑step tutorial on Linux shell programming for beginners, covering variable naming rules, string manipulation, script creation, environment variable handling, arithmetic operations, user input, logical and string operators, as well as common file and directory commands, all illustrated with concrete code examples and screenshots.
1. Variables
Shell variables are assigned without a dollar sign, e.g. your_name="yikoulinux". Rules: use letters, numbers, and underscores; cannot start with a digit; no spaces around the equal sign; usually uppercase. Valid examples:
RUNOOB
LD_LIBRARY_PATH
_var
var2. Invalid examples:
?var=123
user*name=runoob. Common commands: set to list all variables, unset VAR to delete, readonly VAR to make static (cannot unset).
2. String Operations
Built‑in parameter expansion allows length, substring, and replacement. Examples: ${#string} – length of
string ${string:position}– substring from
position ${string:position:length}– substring of
length ${string#substring}– remove shortest matching prefix ${string##substring} – remove longest matching prefix ${string%substring} – remove shortest matching suffix ${string%%substring} – remove longest matching suffix ${string/old/new} – replace first occurrence ${string//old/new} – replace all occurrences
Example to get length:
test='I love china'
echo ${#test} # prints 12Example to extract substring:
echo ${test:5} # e china
echo ${test:4:10} # ve chinaExample to delete prefix/suffix:
test='c:/windows/boot.ini'
echo ${test#/} # c:/windows/boot.ini
echo ${test#*/} # windows/boot.ini
echo ${test##*/} # boot.ini
echo ${test%/*} # c:/windows
echo ${test%%/*} # c:3. Script Creation and Execution
A shell script is a collection of commands saved in a file, usually with .sh extension. The first line (shebang) specifies the interpreter, e.g. #!/bin/bash or #!/bin/sh. Example script first.sh:
#cd /usr/local/sbin
#vim first.sh
#!/bin/bash
## this is my first shell script
# written by 一口Linux 2021.5.3
date
echo "Hello world"Execute with sh first.sh, bash first.sh, ./first.sh (after chmod +x first.sh).
4. Environment Variables
System variables (e.g. HOME, PWD, SHELL, USER) and user‑defined variables. Set with export VAR=value to make it part of the environment, source a file with source file, and view with echo $VAR. Example:
export PATH=$PATH:/home/peng/yikou/
source /etc/bash.bashrc5. Arithmetic
Use expr for integer arithmetic and comparisons. Example:
num1=30
num2=50
expr $num1 + $num2 # addition
expr $num1 - $num2 # subtraction
expr $num1 \* $num2 # multiplication
expr $num1 / $num2 # division
expr $num1 % $num2 # remainder
expr $num1 > $num2 # comparison (returns 1 if true)For loops and conditionals, remember spaces around operators and escape special characters.
6. User Interaction
Positional parameters $0 … $9 hold script name and arguments. $# gives the number of arguments. Use read to get input:
read -p "Please enter your name: " name
echo "Hello $name."Reading multiple values:
read -p "Enter the values: " val1 val2 val3
echo "$val1"
echo "$val2"
echo "$val3"Loop over arguments with $* (single string) or $@ (preserves quoting).
7. Logical Operators
Numeric comparisons: -eq, -ne, -gt, -lt, -ge, -le. Example:
a=10
b=20
if [ $a -gt $b ]; then
echo "a greater than b"
else
echo "a not greater than b"
fi8. String Operators
String comparisons: =, !=, -z (zero length), -n (non‑zero length), and testing if a variable is set with [ $var ]. Example script checks two arguments and reports equality, emptiness, etc.
9. File and Directory Operations
Common tasks:
Extract directory: dirname $path Extract filename: basename $path Batch rename files with spaces using find and sed to replace spaces with underscores.
Read file line‑by‑line: cat file | while read line; do echo $line; done Create a file if it does not exist: [ -f $logFile ] || touch $logFile Recursive directory traversal with a function that calls itself on sub‑directories.
Clear file content: cat /dev/null > $filePath All code snippets above are presented exactly as they appear in the original article, and the accompanying screenshots illustrate the command output.
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.
Linux Tech Enthusiast
Focused on sharing practical Linux technology content, covering Linux fundamentals, applications, tools, as well as databases, operating systems, network security, and other technical knowledge.
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.
