Bash

Idempotent Append to File

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Add a line to a file (e.g., a config or PATH export) only if it isn't already present. Common in install/setup scripts that need to be safe to re-run.
Bash
Raw
ensure_line() {
    local file="$1" line="$2"
    grep -qxF -- "$line" "$file" 2>/dev/null || echo "$line" >> "$file"
}

# Examples
ensure_line ~/.bashrc 'export PATH="$HOME/.local/bin:$PATH"'
ensure_line /etc/hosts "10.0.0.42 git.internal"
ensure_line ~/.gitconfig '[pull]'                            # exact-line match
ensure_line ~/.gitignore_global 'node_modules/'

# Block-replace pattern: replace text between BEGIN/END markers,
# or append the whole block if markers don't exist
ensure_block() {
    local file="$1" tag="$2" content="$3"
    if grep -q "# BEGIN $tag" "$file" 2>/dev/null; then
        sed -i "/# BEGIN $tag/,/# END $tag/c\\
# BEGIN $tag\\
$content\\
# END $tag
" "$file"
    else
        printf '\n# BEGIN %s\n%s\n# END %s\n' "$tag" "$content" "$tag" >> "$file"
    fi
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.