basforge

Search titles, text and the “If it doesn’t work” cases.

    RU

    Bash functions: custom commands with arguments

    A function is a custom command built from one or more commands, where arguments go anywhere you place them: duh /var runs du -h -d1 /var | sort -h. Put functions in the same ~/.bash_aliases file as your aliases, right after them, and call them the same way — by name. Functions don’t work through sudo or inside scripts.

    When an alias isn’t enough

    An alias substitutes text and puts arguments at the end (Bash aliases). That works for a single command with fixed flags. Checking subdirectory sizes takes du -h -d1 /var | sort -h: the path belongs in the middle, between du and |. An alias hands /var to sort, which fails with sort: read failed: /var: Is a directory.

    Another case is creating a directory and jumping into it. That needs the path twice — in mkdir and in cd — and an alias can only append it once at the end.

    Functions handle both. A function is a custom command made of one or more commands, with arguments placed wherever you need them. You call it by name just like an alias: duh /var, mkcd /opt/app.

    How to write a function

    # name() { commands; }
    duh() { du -h -d1 "${1:-.}" 2>/dev/null | sort -h; }

    On one line, you need a space after { and a ; before }. Without either, Bash can’t parse the function body (see “If it doesn’t work” for the exact errors). When a function spans more than one line, split it across lines and drop the semicolon:

    # timestamped backup next to the original — before editing a config
    bak() {
        local copy="$1.bak-$(date +%F-%H%M)"
        sudo cp -a -- "$1" "$copy" && echo "$copy"
    }

    Arguments inside a function:

    Syntax Meaning
    $1, $2 first and second argument
    "$@" all arguments as passed, each as a separate word
    $# number of arguments passed
    ${1:-.} first argument, or . (current directory) if none was passed

    Keep "$1" in double quotes: without them, a path containing a space splits into two arguments.

    Any variable set inside a function stays in your shell after the function returns: if a function sets x=1, echo $x prints 1 afterward. Declare variables with local, like copy in bak, so they stay scoped to the function.

    A function executes inside your current shell, not in a subshell. That’s why cd inside a function changes your working directory, whereas cd inside a script only changes the script’s own directory.

    Where to keep them and in what order

    Keep functions in ~/.bash_aliases. It’s an ordinary Bash script: .bashrc executes it line by line, so everything valid at the prompt works there — aliases, functions, and variables.

    Keep the order aliases first, functions second. Bash expands aliases inside a function once, when it parses the function definition. An alias placed lower in the file won’t exist yet and will fail with command not found at runtime. Once expanded, the alias stays baked into the function — after alias rm='rm -I', clean() { rm "$1"; } is stored as:

    type clean
    # clean is a function
    # clean ()
    # {
    #     rm -I "$1"
    # }

    If you change the alias later, the function picks up the change only when you reload the file.

    Aliases and functions can call each other:

    • An alias can call a function. With alias dlog='duh /var/log', Bash expands the alias text and resolves the first word, duh, as a function. That gives you a shortcut with a baked-in argument.
    • A function can call an alias defined higher up in the file.
    • A function name must not collide with an alias. Bash rejects ll() while the ll alias exists because it expands the alias inside the function header. Run unalias ll first.

    Lookup order when names collide: alias, then function, then Bash builtin, then external program. \name skips only aliases; command name skips both aliases and functions. When wrapping an existing command in a function of the same name, invoke it with command so it doesn’t call itself:

    # list files right after changing directory
    cd() { command cd "$@" && ls; }

    Everyday functions

    # disk usage by directory, largest at the bottom
    duh() { du -h -d1 "${1:-.}" 2>/dev/null | sort -h; }
    
    # create a directory and enter it
    mkcd() { mkdir -p "$1" && cd "$1"; }
    
    # see what listens on a port: port 8080
    port() { sudo ss -tulpn "sport = :$1"; }
    
    # timestamped backup next to the original — before editing a config
    bak() {
        local copy="$1.bak-$(date +%F-%H%M)"
        sudo cp -a -- "$1" "$copy" && echo "$copy"
    }
    
    # shell inside a container: dsh web, dsh web bash
    dsh() { docker exec -it "$1" "${2:-sh}"; }
    • duh with no argument inspects the current directory. Unreadable directories are skipped silently and aren’t counted in the totals.
    • mkcd enters the directory only if mkdir succeeded: && stops cd after an error.
    • port and bak call sudo inside the function. You can’t run a function through sudo, but sudo inside it behaves like any normal command. For a free port, port prints only the header line.
    • bak copies with -a to preserve owner, permissions, and timestamps, then prints the backup name: nginx.conf.bak-2026-11-11-1548.
    • dsh defaults to sh: Alpine-based images don’t ship bash, so dsh web bash returns exec: "bash": executable file not found in $PATH.

    duh and mkcd are already included in Everyday aliases; append port, bak, and dsh to the end of the same file.

    Where functions don’t work

    In the same places as aliases: scripts, ssh web1 'command', and cron. Those run in a fresh Bash that never reads ~/.bash_aliases. Functions also don’t work after sudo: sudo only launches external programs, while functions exist only inside your shell. Adding a trailing space in alias sudo='sudo ' expands aliases, not functions.

    If it doesn’t work

    f() {echo hi} replies syntax error near unexpected token and points at {echo

    Cause
    Without a space after {, Bash reads {echo as one word instead of the start of the function body.
    Fix
    Add a space: f() { echo hi; }.

    After typing f() { echo hi }, the terminal prints > and waits

    Cause
    Without ; before }, Bash treats } as an argument to echo and keeps waiting for the closing brace.
    Fix
    Press Ctrl+C and add ;: f() { echo hi; }. Multi-line functions don’t need trailing semicolons.

    ll() { …; } replies syntax error near unexpected token and points at the parenthesis

    Cause
    ll is an alias in Ubuntu’s .bashrc, so Bash expanded it inside the definition into ls -alF() {. The same happens with l, la, ls, and grep.
    Fix
    Remove the alias first with unalias ll on the line above. Writing function ll { …; } avoids the syntax error, but the alias still wins when you call ll.

    A function prints command not found for an alias that exists in ~/.bash_aliases

    Cause
    The alias is defined below the function. Bash expands aliases inside a function when it parses the definition, and that alias didn’t exist yet.
    Fix
    Put aliases first and functions below them, then reload with source ~/.bash_aliases.

    sudo duh /var replies sudo: duh: command not found

    Cause
    sudo runs external programs, while a function only lives in your shell. export -f duh doesn’t help: sudo doesn’t pass it through.
    Fix
    Put sudo inside the function, as in port and bak. Or run the full command: sudo du -h -d1 /var | sort -h.

    After defining cd() { cd "$@" && ls; }, running cd freezes the terminal and drops the session

    Cause
    cd inside the function calls the same function recursively until Bash runs out of memory. On a 2 GB machine, Bash grew to 1.7 GB before the kernel killed it: Out of memory: Killed process … (bash).
    Fix
    Call command cd inside a function that wraps an existing command: that runs the builtin or binary directly, bypassing aliases and functions.

    A script can’t find your function: command not found

    Cause
    Scripts run in a fresh Bash process, and only interactive shells read ~/.bash_aliases.
    Fix
    Turn commands needed by scripts into scripts in ~/.local/bin (Bash aliases, “Alias, function, or script”).

    How to check

    Confirm the name points to a function and inspect its body:

    type port
    # port is a function
    # port ()
    # {
    #     sudo ss -tulpn "sport = :$1"
    # }

    Test it:

    port 22
    # Netid State  Recv-Q Send-Q Local Address:Port Peer Address:PortProcess
    # tcp   LISTEN 0      4096         0.0.0.0:22        0.0.0.0:*    users:(("sshd",pid=1213,fd=3),("systemd",pid=1,fd=94))
    # tcp   LISTEN 0      4096            [::]:22           [::]:*    users:(("sshd",pid=1213,fd=4),("systemd",pid=1,fd=95))