Environment
Chapter 2: Environment Setup on Arch Linux
Section titled “Chapter 2: Environment Setup on Arch Linux”Overview
Section titled “Overview”This chapter covers setting up your Arch Linux environment for optimal bash scripting. We’ll configure the shell, install essential tools, and set up a productive development environment. This is specifically tailored for DevOps, SRE, and SysAdmin workflows.
Arch Linux Package Management
Section titled “Arch Linux Package Management”Understanding Pacman
Section titled “Understanding Pacman”Arch Linux uses pacman as its package manager. Understanding pacman is crucial for any Arch Linux system administrator.
# Synchronize database and update systemsudo pacman -Syu
# Install a single packagesudo pacman -S package_name
# Install multiple packagessudo pacman -S package1 package2 package3
# Search for packagespacman -Ss search_termpacman -Qs search_term # Search installed
# Remove package onlysudo pacman -R package_name
# Remove package and its dependenciessudo pacman -Rs package_name
# Remove packages that were installed as dependencies but no longer neededsudo pacman -Rsn $(pacman -Qdtq)
# List packagespacman -Q # All installedpacman -Qi package_name # Package infopacman -Ql package_name # List files
# Clean cachesudo pacman -Scc # Clean all cacheEssential Packages for Bash Scripting
Section titled “Essential Packages for Bash Scripting”# Core utilities - absolutely essentialsudo pacman -S \ bash \ bash-completion \ coreutils \ findutils \ gawk \ sed \ grep \ util-linux \ procps-ng \ which \ tree \ htop \ tmux \ vim \ nano \ git \ curl \ wget \ rsync \ cron \ logrotate \ strace \ lsof \ net-tools \ dnsutils \ inetutils \ opensshBash Completion
Section titled “Bash Completion”Installation and Configuration
Section titled “Installation and Configuration”Bash completion is essential for productivity, especially when working with complex commands like kubectl, docker, and terraform.
# Install bash-completionsudo pacman -S bash-completionConfiguration
Section titled “Configuration”Add to your ~/.bashrc:
# Enable bash completionif ! shopt -oq posix; then if [ -f /usr/share/bash-completion/bash_completion ]; then . /usr/share/bash-completion/bash_completion elif [ -f /etc/bash_completion ]; then . /etc/bash_completion fifi
# Additional completions for common DevOps tools# kubectl completionif command -v kubectl &> /dev/null; then source <(kubectl completion bash)fi
# docker completionif command -v docker &> /dev/null; then source /usr/share/bash-completion/completions/dockerfi
# terraform completionif command -v terraform &> /dev/null; then complete -C terraform terraformfiCustom Completions
Section titled “Custom Completions”# Example: Add completion for custom scripts_complete_myapp() { local cur prev COMPREPLY=() cur="${COMP_WORDS[COMP_CWORD]}" prev="${COMP_WORDS[COMP_CWORD-1]}"
case ${COMP_CWORD} in 1) COMPREPLY=($(compgen -W "start stop restart status logs" -- ${cur})) ;; 2) COMPREPLY=($(compgen -W "dev staging production" -- ${cur})) ;; esac
return 0}
complete -F _complete_myapp myappEnvironment Configuration
Section titled “Environment Configuration”The .bashrc File
Section titled “The .bashrc File”Your ~/.bashrc is executed for interactive non-login shells. This is where you configure your daily working environment.
#===============================================================================# HISTORICAL CONFIGURATION#===============================================================================# Don't put duplicate lines in historyHISTCONTROL=ignoredups:ignorespace
# Append to history file (don't overwrite)shopt -s histappend
# History size - important for DevOps workHISTSIZE=10000HISTFILESIZE=20000
# Check window size after each commandshopt -s checkwinsize
# Enable color supportexport CLICOLOR=1
#==============================================================================# PROMPT CONFIGURATION#==============================================================================# Color prompt with Git branchparse_git_branch() { git branch 2>/dev/null | grep '*' | sed 's/* \(.*\)/ (\1)/'}
PS1='\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[01;31m\]$(parse_git_branch)\[\033[00m\]\$ '
#==============================================================================# ALIASES - Essential for DevOps#==============================================================================# Safety aliasesalias rm='rm -iv'alias cp='cp -iv'alias mv='mv -iv'
# List aliasesalias ll='ls -lah'alias la='ls -A'alias l='ls -CF'alias lr='ls -lahR' # Recursive list
# Grep with coloralias grep='grep --color=auto'alias egrep='egrep --color=auto'alias fgrep='fgrep --color=auto'
# DevOps-specific aliasesalias k='kubectl'alias kgp='kubectl get pods'alias kgs='kubectl get services'alias kgd='kubectl get deployments'alias kga='kubectl get all'alias klf='kubectl logs -f'alias kex='kubectl exec -it'
alias d='docker'alias dps='docker ps'alias dpsa='docker ps -a'alias di='docker images'alias dex='docker exec -it'alias dlogs='docker logs -f'
alias tf='terraform'alias tfp='terraform plan'alias tfa='terraform apply'alias tfd='terraform destroy'
# System aliasesalias ports='netstat -tulanp'alias meminfo='free -m -l -t'alias diskspace='df -h'alias folders='du -h --max-depth=1'
#==============================================================================# FUNCTIONS - Reusable for DevOps#==============================================================================# Create directory and cd into itmkcd() { mkdir -p "$1" && cd "$1"}
# Extract common archive formatsextract() { if [ -f "$1" ]; then case "$1" in *.tar.bz2) tar xjf "$1" ;; *.tar.gz) tar xzf "$1" ;; *.bz2) bunzip2 "$1" ;; *.rar) unrar x "$1" ;; *.gz) gunzip "$1" ;; *.tar) tar xf "$1" ;; *.tbz2) tar xjf "$1" ;; *.tgz) tar xzf "$1" ;; *.zip) unzip "$1" ;; *.Z) uncompress "$1" ;; *.7z) 7z x "$1" ;; *) echo "'$1' cannot be extracted via extract()" ;; esac else echo "'$1' is not a valid file" fi}
# Quick kubectl context switchkctx() { if [ -z "$1" ]; then kubectl config get-contexts else kubectl config use-context "$1" fi}
# Docker cleanupdclean() { echo "Stopping all containers..." docker stop $(docker ps -aq) 2>/dev/null || true echo "Removing all containers..." docker rm $(docker ps -aq) 2>/dev/null || true echo "Removing dangling images..." docker image prune -f echo "Cleanup complete!"}
#==============================================================================# ENVIRONMENT VARIABLES#==============================================================================# Editorexport EDITOR=vimexport VISUAL=vimexport PAGER=less
# Less colorsexport LESS='-R'
# Languageexport LANG=en_US.UTF-8export LC_ALL=en_US.UTF-8
# PATH additionsexport PATH="$HOME/bin:$HOME/.local/bin:$PATH"export PATH="$HOME/go/bin:$PATH"# Add Cargo (Rust) if installed[ -d "$HOME/.cargo/bin" ] && export PATH="$HOME/.cargo/bin:$PATH"# Add Flutter if installed[ -d "$HOME/flutter/bin" ] && export PATH="$HOME/flutter/bin:$PATH"
# Kubernetesexport KUBECONFIG="$HOME/.kube/config"
# Dockerexport DOCKER_BUILDKIT=1export COMPOSE_DOCKER_CLI_BUILD=1The .bash_profile File
Section titled “The .bash_profile File”For login shells, use ~/.bash_profile:
# Source .bashrc if it existsif [ -f ~/.bashrc ]; then . ~/.bashrcfiThe .profile File
Section titled “The .profile File”For broader compatibility:
# Set PATHexport PATH="$HOME/bin:$HOME/.local/bin:$PATH"
# Load .bashrc for interactive shellsif [ -n "$BASH_VERSION" ]; then if [ -f "$HOME/.bashrc" ]; then . "$HOME/.bashrc" fifiShell Options
Section titled “Shell Options”Important shopt Options
Section titled “Important shopt Options”# Enable extended globbing - essential for advanced filename matchingshopt -s extglob
# Case-insensitive globbingshopt -s nocaseglob
# Null glob expansion - empty if no matchshopt -s nullglob
# Fail on glob expansion errorsshopt -s failglob
# Append to historyshopt -s histappend
# Check window sizeshopt -s checkwinsize
# Check current optionsshopt
# Check specific optionshopt -q extglob && echo "Enabled" || echo "Disabled"Set Options
Section titled “Set Options”# Common set optionsset -e # Exit on errorset -u # Exit on undefined variableset -o pipefail # Pipeline fails on first errorset -x # Debug mode (trace)set -v # Print input linesText Editor Setup
Section titled “Text Editor Setup”Vim Configuration
Section titled “Vim Configuration”# Install vimsudo pacman -S vim
# Create ~/.vimrc with DevOps-friendly settingscat > ~/.vimrc << 'EOF'"===============================================================================" VIM CONFIGURATION FOR DEVOPS"===============================================================================
" Basic settingsset numberset relativenumberset tabstop=4set shiftwidth=4set expandtabset autoindentset smartindentset wrapset linebreak
" Search settingsset incsearchset hlsearchset ignorecaseset smartcase
" Visual settingssyntax oncolorscheme default
" Key mappingslet mapleader = " "
" Enable mouse supportset mouse=a
" Show line numbersset number
" Highlight current lineset cursorline
" Better backup settingsset nobackupset nowritebackupset noswapfile
" Enable persistent undoset undofileset undodir=~/.vim/undodir
" Custom mappingsnnoremap <leader>w :w<CR>nnoremap <leader>q :q<CR>nnoremap <leader>h :nohlsearch<CR>
" DevOps-specificautocmd FileType yaml setlocal ts=2 sts=2 sw=2 expandtabautocmd FileType json setlocal ts=2 sts=2 sw=2 expandtabautocmd FileType sh setlocal ts=4 sts=4 sw=4 expandtabautocmd FileType dockerfile setlocal ts=4 sts=4 sw=4 expandtabEOF
# Create undodirmkdir -p ~/.vim/undodirGit Configuration
Section titled “Git Configuration”Git Setup for DevOps
Section titled “Git Setup for DevOps”# Install gitsudo pacman -S git
# Configure gitgit config --global user.name "Your Name"git config --global user.email "your.email@example.com"git config --global core.editor vimgit config --global init.defaultBranch main
# Useful git aliasesgit config --global alias.st statusgit config --global alias.co checkoutgit config --global alias.br branchgit config --global alias.ci commitgit config --global alias.lg "log --oneline --graph --all"git config --global alias.last "log -1 HEAD"git config --global alias.unstage "reset HEAD --"
# Color settingsgit config --global color.ui auto
# Pull strategygit config --global pull.rebase false
# Default pushgit config --global push.default currentTerminal Multiplexer
Section titled “Terminal Multiplexer”Tmux Configuration
Section titled “Tmux Configuration”# Install tmuxsudo pacman -S tmux
# Create ~/.tmux.confcat > ~/.tmux.conf << 'EOF'#===============================================================================# TMUX CONFIGURATION#===============================================================================
# Prefix key - use Ctrl+a instead of Ctrl+bset -g prefix C-aunbind C-b
# Allow nested tmux sessionsbind-key C-a send-prefix
# Start window numbering at 1set -g base-index 1set -g pane-base-index 1
# Status barset -g status-interval 5set -g status-left-length 30set -g status-right-length 50set -g status-bg blackset -g status-fg whiteset -g status-left "#[fg=green]#S #[fg=blue]• #[fg=white]"set -g status-right "#[fg=white]%Y-%m-%d %H:%M #[fg=blue]• #[fg=white]"
# Window statussetw -g window-status-format " #I: #W "setw -g window-status-current-format " #I: #W "setw -g window-status-current-style fg=green,bg=black
# Mouse supportset -g mouse on
# Better pane splittingbind-key v split-window -h -c "#{pane_current_path}"bind-key s split-window -v -c "#{pane_current_path}"
# Pane navigationbind-key h select-pane -Lbind-key j select-pane -Dbind-key k select-pane -Ubind-key l select-pane -R
# Resize panesbind-key -r H resize-pane -L 5bind-key -r J resize-pane -D 5bind-key -r K resize-pane -U 5bind-key -r L resize-pane -R 5
# Copy modesetw -g mode-keys vibind-key -T copy-mode-vi v send -X begin-selectionbind-key -T copy-mode-vi y send -X copy-selection-and-cancel
# Reload configbind-key r source-file ~/.tmux.conf \; display "Config reloaded!"EOFAUR Helpers
Section titled “AUR Helpers”Yay Installation
Section titled “Yay Installation”# Install base-devel (required for building from AUR)sudo pacman -S --needed base-devel git
# Clone and install yaygit clone https://aur.archlinux.org/yay.gitcd yaymakepkg -siUsing Yay
Section titled “Using Yay”# Search for packagesyay -Ss package_name
# Install packagesyay -S package_name
# System upgrade (including AUR)yay -Syu
# Remove package and its dependenciesyay -Rsn package_nameCommon AUR Packages for DevOps
Section titled “Common AUR Packages for DevOps”# Install common DevOps tools from AURyay -S \ terraform \ ansible \ packer \ kubectl \ helm \ docker-compose \ k9s \ flux-bin \ argocdEssential DevOps Tools
Section titled “Essential DevOps Tools”Installing Common Tools
Section titled “Installing Common Tools”# Dockersudo pacman -S docker docker-composesudo systemctl enable dockersudo systemctl start dockersudo usermod -aG docker $USER
# Kubernetes toolssudo pacman -S kubectl
# Terraformyay -S terraform
# Ansiblesudo pacman -S ansible
# Python and pipsudo pacman -S python python-pip
# Node.js and npmsudo pacman -S nodejs npm
# Gosudo pacman -S go
# AWS CLIpip install awscli --break-system-packages
# GCP CLIyay -S google-cloud-sdk
# Azure CLIyay -S azure-cliDirectory Structure
Section titled “Directory Structure”Recommended Project Structure
Section titled “Recommended Project Structure”~/bash-scripts/├── bin/ # Executable scripts│ ├── deploy.sh│ ├── backup.sh│ └── monitor.sh├── lib/ # Shared libraries│ ├── common.sh│ ├── utils.sh│ └── config.sh├── config/ # Configuration files│ ├── app.conf│ └── .env├── logs/ # Log files│ └── .gitkeep├── tests/ # Test scripts│ └── test_utils.sh├── docs/ # Documentation├── README.md # Project README├── Makefile # Build automation└── .gitignore # Git ignore rulesCreate the Structure
Section titled “Create the Structure”mkdir -p ~/bash-scripts/{bin,lib,config,logs,tests,docs}touch ~/bash-scripts/logs/.gitkeepEnvironment Variables for Scripting
Section titled “Environment Variables for Scripting”Essential Variables
Section titled “Essential Variables”# Add to ~/.bashrc
# History configurationexport HISTSIZE=10000export HISTFILESIZE=20000export HISTCONTROL=ignoredups:ignorespace
# Languageexport LANG=en_US.UTF-8export LC_ALL=en_US.UTF-8
# Editorexport EDITOR=vimexport VISUAL=vimexport PAGER=less
# PATH additionsexport PATH="$HOME/bin:$HOME/.local/bin:$PATH"export PATH="$HOME/go/bin:$PATH"
# Kubernetesexport KUBECONFIG="$HOME/.kube/config"
# Dockerexport DOCKER_BUILDKIT=1export COMPOSE_DOCKER_CLI_BUILD=1
# Goexport GOPATH="$HOME/go"export PATH="$PATH:$GOPATH/bin"
# AWSexport AWS_DEFAULT_REGION=us-east-1Quick Reference: Arch Linux Commands
Section titled “Quick Reference: Arch Linux Commands”┌─────────────────────────────────────────────────────────────────────┐│ ARCH LINUX QUICK REFERENCE │└─────────────────────────────────────────────────────────────────────┘
┌──────────────────┬─────────────────────────────────────────────────┐│ Command │ Description │├──────────────────┼─────────────────────────────────────────────────┤│ pacman -Syu │ Full system upgrade ││ pacman -S <pkg> │ Install package ││ pacman -R <pkg> │ Remove package ││ pacman -Qs <pkg> │ Search installed packages ││ pacman -Qdt │ List orphans (unused dependencies) ││ pacman -Qe │ List explicitly installed packages ││ pacman -Qi <pkg> │ Package information ││ pacman -Ql <pkg> │ List package files ││ pacman -Fs <file>│ Find which package provides file ││ yay -S <pkg> │ Install from AUR ││ yay -Syu │ Full system upgrade (including AUR) ││ systemctl │ Manage systemd services ││ journalctl │ View system logs ││ hostnamectl │ System information ││ timedatectl │ Time and date settings ││ localectl │ Locale settings ││ loginctl │ User session management │└──────────────────┴─────────────────────────────────────────────────┘Testing Your Setup
Section titled “Testing Your Setup”Verify Bash Version
Section titled “Verify Bash Version”# Check bash version - should be 5.x on Arch Linuxbash --version
# Verify bash featuresecho $BASH_VERSIONTest Completions
Section titled “Test Completions”# Source bashrcsource ~/.bashrc
# Test completionsudo pacman -S<tab><tab>kubectl<tab><tab>docker<tab><tab>Test Script Execution
Section titled “Test Script Execution”# Create test scriptcat > /tmp/test.sh << 'EOF'#!/bin/bash# Test script for environment verification
set -euo pipefail
echo "==============================================="echo "Bash Environment Test"echo "==============================================="echo "Bash version: $BASH_VERSION"echo "Working directory: $(pwd)"echo "Home directory: $HOME"echo "User: $USER"echo "Hostname: $HOSTNAME"echo "==============================================="
# Test essential commandsecho -n "Testing essential commands: "
commands=("grep" "awk" "sed" "find" "curl" "wget" "git")all_ok=true
for cmd in "${commands[@]}"; do if command -v "$cmd" &> /dev/null; then echo -n "✓ " else echo -n "✗ ($cmd missing) " all_ok=false fidoneecho
if [ "$all_ok" = true ]; then echo "All essential commands available!" exit 0else echo "Some commands are missing. Install them with: sudo pacman -S ..." exit 1fiEOF
chmod +x /tmp/test.sh/tmp/test.shSummary
Section titled “Summary”Your Arch Linux environment is now configured for bash scripting:
- ✅ Pacman and AUR configured
- ✅ Bash completion enabled
- ✅ Custom prompt with Git support
- ✅ Essential DevOps tools installed
- ✅ Text editor configured
- ✅ Git configured
- ✅ Tmux configured
- ✅ Project structure created
Exercises
Section titled “Exercises”Level 1: Basics
Section titled “Level 1: Basics”- Configure your bash environment with aliases for kubectl and docker
- Install additional tools you need for your daily work
- Create your project directory structure
Level 2: Intermediate
Section titled “Level 2: Intermediate”- Install and configure tmux with custom settings
- Set up vim with YAML and Python support
- Configure kubectl completion
Level 3: Advanced
Section titled “Level 3: Advanced”- Create a script that auto-installs your preferred environment
- Set up a custom prompt with Kubernetes context display
- Configure dotfiles repository for your configuration
Next Steps
Section titled “Next Steps”In the next chapter, we’ll write your first bash script and learn the basic syntax.
Previous Chapter: Introduction to Bash Next Chapter: Basic Syntax and First Script