Master Linux Shell: Variables, Strings, and Script Essentials
This guide explains how to use and name shell variables, manipulate strings, create and run Bash scripts, manage environment variables, perform arithmetic and relational operations, read user input, and handle common file‑system tasks, providing clear examples and command‑line snippets for each topic.
Variable Usage
When defining a Bash variable, omit the leading $ and do not place spaces around the equal sign, e.g. your_name="yikoulinux". Variable names may contain letters, digits and underscores, must not start with a digit, must not use punctuation or Bash reserved words, and are conventionally uppercase.
Valid: RUNOOB, LD_LIBRARY_PATH, _var, var2 Invalid: ?var=123, user*name=runoob Shell variables are divided into system variables (e.g. PWD, USER, HOME) and user‑defined variables.
Define a variable: variable=value List all variables: set Remove a variable: unset variable Make a variable read‑only: readonly variable (cannot be unset)
Assign a command’s output: A=$(ls -la) (equivalent to back‑ticks `ls -la`)
String Operations
Bash provides built‑in parameter expansion for common string manipulations, which is faster than invoking external tools. ${#string} – length of
string ${string:position}– substring from position to the end ${string:position:length} – length characters starting at
position ${string#substring}– remove shortest matching substring from the beginning ${string##substring} – remove longest matching substring from the beginning ${string%substring} – remove shortest matching substring from the end ${string%%substring} – remove longest matching substring from the end ${string/substring/replacement} – replace first occurrence of
substring ${string//substring/replacement}– replace all occurrences of
substring ${string/#substring/replacement}– replace substring if it appears at the start ${string/%substring/replacement} – replace substring if it appears at the end
Examples:
test="I love china"
# Length
echo ${#test} # 12
# Substring
echo ${test:5} # e china
echo ${test:5:10} # e china
# Delete prefix
path="c:/windows/boot.ini"
echo ${path#/} # c:/windows/boot.ini
echo ${path#*/} # windows/boot.ini
echo ${path##*/} # boot.ini
# Replace characters
echo ${path/\//\\} # c:\windows/boot.iniScript Creation and Execution
A Bash script is a plain‑text file (usually with a .sh extension) that contains commands. The first line should specify the interpreter, e.g.:
#!/bin/bashComments start with #. To run a script you can use any of the following:
sh script.sh bash script.sh ./script.sh(after chmod +x script.sh)
Environment Variables
Export a variable to make it available to child processes:
export VAR_NAME=value
source ~/.bashrc # reload configuration
echo $VAR_NAMECommon environment variables include HOME and PATH:
echo $HOME
echo $PATHArithmetic Operations
Use expr for integer arithmetic and comparisons. Example:
num1=30
num2=50
expr $num1 \> $num2 # 0 (false)
expr $num1 \< $num2 # 1 (true)
expr $num1 + $num2 # addition
expr $num1 - $num2 # subtraction
expr $num1 \* $num2 # multiplication
expr $num1 / $num2 # division
expr $num1 % $num2 # remainderScript Interaction with Users
Positional parameters $1, $2, … hold command‑line arguments. $# gives the number of arguments, $* treats all arguments as a single string, and $@ treats them as separate words.
#!/bin/bash
for ((i=1; i<=$#; i++))
do
echo "Param $i is: ${!i}"
doneThe read builtin reads input from the user. Useful options: -p "prompt" – display a prompt -t seconds – timeout -n N – read at most N characters
read -p "Please enter your name: " name
echo "Hello $name"Example that validates a positive integer and computes the sum 1+2+…+n:
#!/bin/bash
while true; do
read -p "please input a positive number: " num
expr $num + 1 &>/dev/null
if [ $? -eq 0 ]; then
if [ $(expr $num \> 0) -eq 1 ]; then
sum=0
for i in $(seq 1 $num); do
sum=$(expr $sum + $i)
done
echo "1+2+...+$num = $sum"
exit
fi
fi
echo "error, input illegal"
continue
doneRelational Operators
Within [ ] tests Bash supports the following integer comparison operators: -eq – equal -ne – not equal -gt – greater than -lt – less than -ge – greater than or equal -le – less than or equal
a=10
b=20
if [ $a -gt $b ]; then
echo "a greater than b"
else
echo "a not greater than b"
fiString Comparison Operators
String tests in [ ] include: = – equal != – not equal -z – length is zero -n – length is non‑zero $var – true if variable is non‑empty
#!/bin/bash
if [ -z "$1" ]; then
echo "First argument is empty"
else
if [ "$1" = "$2" ]; then
echo "$1 equals $2"
else
echo "$1 does not equal $2"
fi
fiCommon File and Directory Operations
Extract directory name: dirname $path Extract file name: basename $path Batch rename files containing spaces:
function processFilePathWithSpace() {
find $1 -name "* *" | while read line; do
newFile=$(echo "$line" | sed 's/[ ][ ]*/_/g')
mv "$line" "$newFile"
done
}Read a file line‑by‑line:
while read line; do
echo "$line"
done < /tmp/text.txtCreate a file if it does not exist:
[ -f $logFile ] || touch $logFileRecursive directory traversal:
function getFile() {
for file in $(ls $1); do
element="$1/$file"
if [ -d $element ]; then
getFile $element
else
echo $element
fi
done
}Clear a file’s contents:
cat /dev/null > $filePathSigned-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.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
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.
