Bash: ‘Ambiguous Redirect’ error
1 min readNov 18, 2021
The aim of this page📝is to see what happens if you redirect into a file with an empty string in it.
- Lesson: in general it is always good to use double-quote for user variables to prevent things like
ambiguous redirect
error when values with space in it get evaluated/parsed as two strings instead of one.
1. broken code
date=$(date)
topic=$1
filename=./${topic}notes.txt
read -p "Your note:" note
echo Note '$note' saved to $filename
echo $date: $note >>$filename
>>> ./b13_05.sh "other things"
Your note:Note
Note $note saved to ./other thingsnotes.txt
./b13_05.sh: line 6: $filename: ambiguous redirect
2. ambiguous redirect
- bash sees the redirection in
$note >>$filename
$filename
evaluates to./other stuffnotes.txt
which, unless quoted — is ambiguous for its interpreter- it sees it followed by multiple words with spaces between them
- this is confusing — redirection is allowed for a single file
- to fix this the variable itself has to be quoted
3. fixed code
- ✅ use quotes around user vars
- ✅ use brackets when combining symbols and literals
date=$(date)
topic="$1"
filename="./${topic}notes.txt"
read -p "Your note:" note
echo "Note '$note' saved to $filename"
echo "$date: $note" >>"$filename"