Fundamentals of Shell Scripting

Script Structure and Execution

Shell scripts require a shebang line at the beginning to specify the interpreter:

#!/bin/bash
#!/usr/bin/python3

Comments use the # symbol and are single-line only. To execute a script:

chmod +x script.sh
./script.sh

Input and Output

Reading input with read:

read input_var
read -p "Enter value: " prompt_var
read -sp "Password: " pass_var
read -a array_input

Output with echo:

echo -e "Line1\nLine2"
echo -e "\e[1;31mRed text\e[0m"

Redirection examples:

command >> file.log 2>/dev/null
command >> output.log 2>&1

Variables and Data Types

Variable assignment and usage:

username="developer"
echo "User: ${username}"

Special variables:

  • $? - Exit status of last command
  • $0 - Script name
  • $# - Number of arguments
  • $@ - All arguments

Quoting differences:

single='Literal $text'
double="Interpolated ${username}"
command=$(ls -l)

String Operations

String length and manipulation:

text="example"
echo ${#text}
echo ${text:2:4}
echo ${text: -3}

Control Structures

Conditional statements:

if [ $status -eq 0 ]; then
    echo "Success"
elif [ -f "$file" ]; then
    echo "File exists"
else
    echo "Failure"
fi

Case statement:

case $input in
    "start") echo "Beginning" ;;
    "stop") echo "Ending" ;;
    *) echo "Unknown" ;;
esac

Loop structures:

for item in $(ls); do
    echo $item
done

while read line; do
    echo $line
done < data.txt

Functions

Function definition and usage:

process_data() {
    local result=$1
    echo "Processing: $result"
}

process_data "sample"

Arrays

Array operations:

items=("first" "second" 123)
echo ${items[1]}
items[1]="updated"

for element in "${items[@]}"; do
    echo $element
done

Date and Time

Date formatting and calculations:

date +"%Y-%m-%d"
date -d "1 day ago" +"%F"
date -d "@1511234976" +"%T"
date +"%s"

Useful Commands

File operations:

ls -alh
find /path -name "*.txt" -size +1M
grep -v "exclude" file.txt
du -h --max-depth=2

Text processing:

sort -nr file.txt | uniq -c
tr -d '\r' < windows_file.txt
wc -l document.txt

Path manipulation:

basename /path/to/file.txt
dirname /path/to/file.txt

Text Processing Tools

sed examples:

sed -i 's/old/new/g' file.txt
sed -n '1,5p' data.txt

awk examples:

awk -F: '{print $1, $NF}' /etc/passwd
awk 'NR==2,NR==5 {print $2}' data.txt

Script Debugging

Debugging techniques:

bash -n script.sh
bash -x script.sh
export LANG="en_US.UTF-8"
nohup ./script.sh &

Tags: bash shell-scripting Linux command-line text-processing

Posted on Mon, 18 May 2026 04:51:00 +0000 by BIOSTALL