Bash error: "ambiguous redirect"

Bash prints "ambiguous redirect" when a redirection target expands to multiple words because of unquoted variables. Here is the fix.

Error String

bash: $VAR: ambiguous redirect

Tldr

Bash redirections accept a single filename. When the variable holding the target is unquoted and contains whitespace, it word-splits into multiple words and Bash refuses with "ambiguous redirect". Quote the variable to fix it.

Cause

Operators like > and >> need exactly one target. An unquoted expansion that produces zero or multiple words violates that. The same applies when the variable is empty (zero words).

Repro

#!/usr/bin/env bash
out="my log.txt"
echo hello > $out          # ambiguous redirect (word-splits to two)
echo hello > $missing      # ambiguous redirect (empty)

Fix

#!/usr/bin/env bash
out="my log.txt"
echo hello > "$out"
echo hello > "${missing:?target is empty}"

Explanation

Always quote redirection targets. Pair with the ${var:?msg} form when the variable could be empty — you get a clear error instead of a silent miss.

Related Shellcheck

SC2086

Faq

Q

Why does Bash require exactly one word here?

A

Redirections are positional — Bash has nowhere to put the second filename and refuses rather than guessing.

Q

Does this affect heredocs?

A

Heredoc bodies are subject to expansion but not splitting, so they don't hit this error. Heredoc redirections (`<<EOF >file`) still need quoted targets.

Q

Why does quoting change the error?

A

Quoting guarantees exactly one word, so a multi-word value becomes a single (odd) filename rather than an ambiguous target.

Q

Is &> portable?

A

It is Bash-specific. Use `> file 2>&1` in POSIX `sh` scripts.

Deep Dive

Heading

The target expanded to zero or several words

Body

Bash needs exactly one word after `>` or `<`. An unset or empty variable leaves nothing, and a variable containing spaces or a glob that matched several files leaves too many — both produce "ambiguous redirect". Quoting the target solves the multi-word case: `> "$logfile"`. For the empty case, quoting turns the error into an attempt to open a file named the empty string, so validate first with `[ -n "$logfile" ]` and fail with a message the operator can act on.

Heading

Typos in file descriptor syntax

Body

The same message appears when `>&` is used with a target that is not a number or a valid descriptor: `2>&1` redirects stderr to stdout, but `2>& 1` with a space, or `2>&file`, is invalid. To send both streams to a file use `cmd > file 2>&1` (order matters) or the Bash shorthand `cmd &> file`. Remember that `2>&1 > file` sends stderr to the old stdout — the terminal — and only then redirects stdout, which is almost never what is intended.

Checklist

Quote the redirection target.

Validate the variable is non-empty before redirecting.

Use `> file 2>&1` in that order to capture both streams.

Check for a stray space in `>&` sequences.