Why names are harder than they look
People think of a file name as a word, but the kernel does not. On Linux, a name is any byte string that does not contain a slash or a NUL byte. The name my notes.txt has a space, report (final).pdf has parentheses, and a name can even contain a newline. A program that splits its input on whitespace will see these names as several names, and a program that reads options will see a name that begins with a dash as an option. Both mistakes come from treating file names as text that the shell has already cleaned up for you.
Consider the simplest task: remove a file called -draft.txt. Typing rm -draft.txt fails, because rm reads the dash as the start of an option cluster and finds letters it does not know. The reliable answer is the end-of-options marker, a pair of dashes on a line by itself.
touch -- -draft.txt
rm -- -draft.txtEvery standard utility follows the convention that -- ends option parsing, so anything after it is a file name, even if it begins with a dash. Use it with rm, mv, cp, touch, ls, and any program that accepts files. A relative alternative is to prefix the name with ./, which also prevents the leading dash from being read as an option.
Always quote expansions
The main defense against spaces is quoting. An unquoted variable is split at spaces, tabs, and newlines, and each piece becomes an argument. A quoted variable stays one argument. The difference shows up immediately with a name that has a space.
f='my notes.txt'
touch "$f"
ls -l $f
ls -l "$f"The unquoted ls asks for two files, my and notes.txt, and reports that the first does not exist. The quoted form asks for the one file you meant. Quote every variable and every command substitution that holds a path, and you will avoid most of these failures without thinking about them.
Globs are safe, output parsing is not
Filename expansion is not affected by spaces. A pattern such as *.txt expands into a list of names, and each name becomes one argument, even if it contains spaces. That makes for f in *.txt a safe way to loop over the files in the current directory, because the loop variable receives each name whole. The trouble starts when you pipe ls into a loop, because the output of ls is text in which names are separated by newlines. A name that contains a newline breaks the loop into two names, and nothing in the output tells you so.
For a full listing that must handle any name, do not parse ls. Ask find to print each name followed by a NUL byte, and read those records in a loop. The NUL byte cannot appear in a file name, so it is an unambiguous separator.
find . -maxdepth 1 -type f -print0 |
while IFS= read -r -d '' f; do
printf '[%s]\n' "$f"
doneThe pieces of this idiom each do one job. The -print0 option makes find emit NUL separators. The -d '' option tells read to stop at a NUL. The empty IFS= preserves leading and trailing spaces, and -r keeps backslashes as they are. Learn the whole pattern once, because it is the right tool whenever the names are not under your control.
Names with newlines
A name with a newline is rare, but it appears in downloaded archives, and it is the case that exposes line-based scripts. You can create one with the ANSI-C form, which the quoting lesson introduced. Once the file exists, ls shows a question mark or a visible escape depending on the terminal, and a line-based loop would process two broken names. The NUL-separated loop above handles it correctly, because the newline is just another byte inside the record.
touch $'new\nline.txt'
ls -bThe -b option of ls escapes unprintable characters, so the output shows the newline as a backslash sequence. That display is for humans. Scripts should never use the displayed form as a file name.
Moving and copying safely
When you move a file, quote both names and put -- before them. Without the marker, a source name that begins with a dash would be read as an option, and a missing quote would split the name. A clean form is mv -- "$src" "$dst". If the destination might already exist, check first with a test, because mv silently overwrites a regular file by default. The rename script in this module does exactly that check before it moves anything. Keep in mind that a check followed by a move is not atomic. Another process could create the target between the two steps, so a script that must be safe against concurrent writers needs a different tool, such as the no-clobber option of a copy command, or a lock.
Names that begin with a dash in redirections
The end-of-options marker is for command arguments. A redirection target is not an option, so echo hi > -notes.txt creates the file without trouble. The problem appears on the next line, when you read it back with cat -notes.txt, which fails because cat reads the dash as an option. The fix is the same as before, either cat -- -notes.txt or the prefix cat ./-notes.txt. Remembering which parts of a command are options and which are operands is what makes these fixes obvious.
A checklist for scripts
Read each command that touches a path and ask four questions. Is every expansion quoted? Is there a -- before any name that could begin with a dash? Does the loop use NUL-separated records when names are not under your control? Does the command overwrite anything, and is that intended? If you can answer yes to all four, the script will survive most real directories, including the one with a name that nobody expected.