🦉 FreeBSD Shell Basics
FreeBSD provides a robust shell environment with both traditional Bourne shell compatibility and modern enhancements. This guide covers essential shell concepts and FreeBSD-specific features.
🎯 Shell Environment Overview
Default Shell
FreeBSD uses different default shells depending on the version and user type:
1
2
3
4
5
6
7
8
9
10
11
12 | # Check current shell
echo $SHELL
# System default shell
ls -la /bin/sh # Usually points to /bin/sh (POSIX shell)
# User default shell
grep "^username:" /etc/passwd # Shows user's shell
# Change user shell
chsh -s /bin/tcsh username # Change to tcsh
chsh -s /usr/local/bin/bash username # Change to bash
|
Available Shells
| # List available shells
cat /etc/shells
# Common FreeBSD shells:
# /bin/sh - POSIX compliant shell
# /bin/csh - C Shell
# /bin/tcsh - Enhanced C Shell
# /usr/local/bin/bash - GNU Bash
# /usr/local/bin/zsh - Z Shell
# /bin/ksh - Korn Shell
# /bin/ksh93 - Korn Shell 93
|
🔧 Shell Configuration Files
Login Shell Configuration
1
2
3
4
5
6
7
8
9
10
11
12
13 | # System-wide configuration
/etc/profile # Bourne shell family login
/etc/csh.login # C shell family login
# User-specific configuration
~/.profile # Bourne shell family
~/.login # C shell family
# Shell-specific configuration
~/.bashrc # Bash interactive
~/.bash_profile # Bash login
~/.zshrc # Zsh interactive
~/.cshrc # C shell interactive
|
Shell Initialization Order
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 | # Bourne shell family (sh, bash, ksh, zsh in sh mode)
# Login shell:
# 1. /etc/profile
# 2. ~/.bash_profile (bash) or ~/.profile (sh/ksh)
# 3. ~/.bashrc (if sourced from .bash_profile)
# Non-login interactive shell:
# 1. ~/.bashrc
# C shell family (csh, tcsh)
# Login shell:
# 1. /etc/csh.cshrc
# 2. /etc/csh.login
# 3. ~/.cshrc
# 4. ~/.login
# Non-login interactive shell:
# 1. /etc/csh.cshrc
# 2. ~/.cshrc
|
📋 Environment Variables
FreeBSD-Specific Variables
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 | # System information
echo $HOSTTYPE # Architecture (amd64, i386, etc.)
echo $OSTYPE # Operating system (FreeBSD)
echo $MACHTYPE # Machine type
echo $USER # Current user
echo $HOME # Home directory
echo $PATH # Command search path
# FreeBSD-specific paths
echo $PREFIX # /usr/local (default)
echo $LOCALBASE # /usr/local (ports/packages)
# Shell configuration
echo $SHELL # Current shell
echo $TERM # Terminal type
echo $PAGER # Default pager (more, less)
echo $EDITOR # Default editor
|
Setting Environment Variables
1
2
3
4
5
6
7
8
9
10
11
12
13 | # Temporary variables (current session only)
export MYVAR="value"
MYVAR="value" export # Alternative syntax
# Persistent variables in ~/.profile or ~/.bash_profile
echo 'export MYVAR="value"' >> ~/.profile
# System-wide variables in /etc/profile
# (requires root access)
echo 'export SYSTEM_VAR="value"' >> /etc/profile
# C shell syntax (in ~/.cshrc or ~/.login)
setenv MYVAR "value"
|
🔍 Command Line Editing
Line Editing Features
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 | # Emacs mode (default for most shells)
Ctrl+A # Beginning of line
Ctrl+E # End of line
Ctrl+B # Backward character
Ctrl+F # Forward character
Ctrl+P # Previous command (up arrow)
Ctrl+N # Next command (down arrow)
Ctrl+D # Delete character/Delete session
Ctrl+K # Kill to end of line
Ctrl+U # Kill to beginning of line
Ctrl+W # Kill word backward
Ctrl+Y # Yank (paste killed text)
Ctrl+R # Reverse search history
Ctrl+L # Clear screen
Tab # Command/file completion
# Vi mode (alternative)
set -o vi # Enable vi mode in sh/bash
bindkey -v # Enable vi mode in zsh
|
History Management
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 | # History navigation
!! # Previous command
!n # Command number n
!string # Most recent command starting with string
!?string # Most recent command containing string
^old^new # Substitute in previous command
# History manipulation
history # Show command history
fc # Fix command (edit and re-execute)
history -c # Clear history
history -d n # Delete history entry n
# History configuration
export HISTSIZE=1000 # History size
export HISTFILESIZE=2000 # History file size
export HISTCONTROL=ignoredups # Ignore duplicates
|
🛠️ File and Directory Operations
FreeBSD File System Features
1
2
3
4
5
6
7
8
9
10
11
12 | # Soft Updates (default in FreeBSD)
# Provides better performance and reliability
# UFS (Unix File System) features
tunefs -n enable / # Enable soft updates
dump -0uf /backup/root.dump / # Full filesystem backup
restore -rf /backup/root.dump # Restore filesystem
# ZFS support (if installed)
zpool list # List ZFS pools
zfs list # List ZFS filesystems
zfs create tank/home # Create ZFS filesystem
|
File Permissions and Attributes
1
2
3
4
5
6
7
8
9
10
11
12
13
14 | # Traditional permissions
chmod 755 filename # Set permissions
chown user:group filename # Change ownership
ls -l filename # Show permissions
# FreeBSD extended attributes
ls -@ filename # Show extended attributes
setextattr user key value filename # Set extended attribute
getextattr -q user key filename # Get extended attribute
# File flags (BSD-specific)
chflags schg filename # Set system immutable flag
chflags sunlnk filename # Set system undeletable flag
ls -lo filename # Show file flags
|
📊 Process Management
FreeBSD Process Control
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | # Process viewing
ps aux # All processes
ps -auxwww # Detailed view
top # Interactive process viewer
htop # Enhanced top (if installed)
# Process manipulation
kill PID # Terminate process
kill -9 PID # Force terminate
killall processname # Kill by name
pkill pattern # Kill by pattern matching
# FreeBSD-specific tools
procstat PID # Detailed process information
fstat # Open files by process
sockstat # Socket statistics
|
Job Control
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 | # Background processes
command & # Run in background
jobs # List jobs
fg %n # Foreground job n
bg %n # Background job n
kill %n # Kill job n
# Process priority
nice -n 10 command # Run with lower priority
renice 5 PID # Change priority of running process
# Resource limits
ulimit -a # Show all limits
ulimit -u 100 # Limit processes
ulimit -f 1000000 # Limit file size
|
🌐 Network Operations
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | # Interface configuration
ifconfig # Show all interfaces
ifconfig em0 # Show specific interface
ifconfig em0 inet 192.168.1.100 # Configure interface
# Network information
netstat -rn # Routing table
netstat -an # All connections
sockstat # Socket statistics (FreeBSD specific)
arp -a # ARP table
# Network diagnostics
ping host # ICMP ping
traceroute host # Route tracing
dig domain # DNS lookup
nslookup domain # DNS query
|
Network Services
1
2
3
4
5
6
7
8
9
10
11
12
13 | # Service management
service sshd status # Check SSH status
service nginx start # Start web server
service postgresql restart # Restart database
# FreeBSD-specific services
service -l # List all services
service -r # List running services
service -e # List enabled services
# Configuration files
/etc/rc.conf # Service enablement
/usr/local/etc/ # Third-party service configs
|
🎨 Shell Programming Features
FreeBSD Shell Extensions
1
2
3
4
5
6
7
8
9
10
11
12
13
14 | # Parameter expansion (sh/bash)
${var:-default} # Use default if unset
${var:=default} # Set and use default
${var:+value} # Use value if set
${var#pattern} # Remove from beginning
${var%pattern} # Remove from end
# Command substitution
result=$(command) # Modern syntax
result=`command` # Traditional syntax
# Arithmetic expansion
result=$((expression)) # Arithmetic evaluation
let var=expression # Variable assignment
|
Flow Control
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 | # Conditional statements
if [ condition ]; then
# commands
elif [ condition ]; then
# commands
else
# commands
fi
# Case statements
case "$variable" in
pattern1)
# commands
;;
pattern2|pattern3)
# commands
;;
*)
# default commands
;;
esac
# Loops
for item in list; do
# commands
done
while [ condition ]; do
# commands
done
until [ condition ]; do
# commands
done
|
🧪 Advanced Shell Features
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 | # Standard redirection
command > file # Standard output to file
command < file # Standard input from file
command 2> file # Standard error to file
command >& file # Both output and error to file
command >> file # Append to file
# Here documents
cat << EOF
Multi-line input
Variable expansion: $HOME
EOF
# Here strings
command <<< "single line input"
# Process substitution
diff <(sort file1) <(sort file2)
|
Functions and Aliases
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 | # Function definition
my_function() {
local arg1="$1"
local arg2="$2"
echo "Arguments: $arg1, $arg2"
}
# Function with local variables
calculate_sum() {
local num1="$1"
local num2="$2"
local sum=$((num1 + num2))
echo "$sum"
}
# Aliases
alias ll='ls -la'
alias grep='grep --color=auto'
alias ..='cd ..'
# Permanent aliases in ~/.bashrc or ~/.zshrc
echo "alias ll='ls -la'" >> ~/.bashrc
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 | # System information
uname -a # System information
freebsd-version # FreeBSD version
sysctl hw.physmem # Physical memory
sysctl kern.hostname # Hostname
# Package management
pkg info # Installed packages
pkg search package # Search packages
pkg install package # Install package
pkg delete package # Remove package
# Ports system
cd /usr/ports/category/port
make install clean # Build and install from ports
# System monitoring
dmesg # Boot messages
vmstat # Virtual memory statistics
iostat # I/O statistics
systat # Interactive system monitor
|
1
2
3
4
5
6
7
8
9
10
11
12
13 | # File integrity
mtree -c -K sha256 -p /etc > /etc/mtree.conf # Create manifest
mtree -f /etc/mtree.conf # Verify integrity
# Security auditing
pkg audit # Check for vulnerable packages
portaudit -F # Fetch vulnerability database
portaudit -a # Audit installed packages
# Process monitoring
procstat -f PID # File descriptors
procstat -j PID # Jails
procstat -v PID # Virtual memory
|
🎨 Customization Examples
Shell Prompt Customization
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 | # Bash prompt
PS1='\u@\h:\w\$ ' # Basic prompt
PS1='\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
# Zsh prompt
PROMPT='%n@%m:%~%# ' # Basic prompt
PROMPT='%F{green}%n%f@%F{blue}%m%f:%F{yellow}%~%f %# '
# C shell prompt
set prompt="%n@%m:%~ %# "
# Dynamic prompt with git branch
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
PS1='\u@\h:\w \$(parse_git_branch)\$ '
|
Useful Shell Functions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 | # Directory navigation
mkcd() {
mkdir -p "$1" && cd "$1"
}
# Extract any archive
extract() {
if [ -f "$1" ]; then
case "$1" in
*.tar.bz2) tar -xjf "$1" ;;
*.tar.gz) tar -xzf "$1" ;;
*.bz2) bunzip2 "$1" ;;
*.gz) gunzip "$1" ;;
*.tar) tar -xf "$1" ;;
*.zip) unzip "$1" ;;
*.rar) unrar x "$1" ;;
*) echo "Unknown archive format" ;;
esac
else
echo "'$1' is not a valid file"
fi
}
# Quick backup
backup() {
if [ -f "$1" ]; then
cp "$1"{,.bak}
echo "Backup created: $1.bak"
else
echo "File not found: $1"
fi
}
|
🧾 Summary Commands
Essential FreeBSD Commands
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 | # System information
uname -a # System details
freebsd-version # Version information
sysctl -a # All system parameters
# Package management
pkg info # Installed packages
pkg search term # Search packages
pkg install package # Install package
# Service management
service -l # List services
service name start # Start service
sysrc name_enable=YES # Enable service
# Process management
ps aux # All processes
top # Process monitor
procstat PID # Process details
# File operations
ls -@ # Show extended attributes
chflags flags file # Set file flags
mtree # File integrity
|
Shell Customization
| # Configuration files
~/.profile # Bourne shell login
~/.bashrc # Bash interactive
~/.zshrc # Zsh interactive
~/.cshrc # C shell interactive
# Environment variables
export PATH="/usr/local/bin:$PATH" # Add local bin
export EDITOR=vim # Set default editor
export PAGER=less # Set default pager
|
🧾 See Also