Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 95 ยท Working with Files

Creating and Viewing Files

Create files and directories with touch, mkdir -p, echo, printf and here-docs, then inspect them with cat, wc, file and stat. Includes tips for file names with spaces.

You now know how the filesystem is laid out and how to move around it. This lesson is where you start putting things in it. On Linux a file is just a sequence of bytes with a name, and there are several quick ways to make one: ask for an empty file, redirect the output of a command into it, or write a multi-line block of text with a here-document. Then you need to look at what you made, which means printing it, counting it, and asking the system what kind of file it is.

You will learn touch, mkdir, echo, printf, cat, wc, file and stat, the difference between > and >>, how to create many files at once, and how to deal with file names that contain spaces. Copying and deleting come next in Copying, Moving and Deleting. Everything here runs in a temporary directory that disappears after each run, so experiment freely.

Empty files and directories

touch name creates an empty file if it does not exist. If the file already exists, touch leaves the contents alone and only updates its modification time, which is the original purpose of the command. You can pass several names at once.

mkdir name creates a directory. It refuses to create a directory that exists, and it cannot create a/b/c if a/b is missing. The option -p ("parents") solves both: it creates every missing level and is silent when the directory already exists, so it is safe to repeat in scripts.

Bash touch and mkdir -p

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The first ls prints one.txt, project, three.txt and two.txt; the recursive listing shows the nested directories. Running mkdir -p a second time is harmless. Without -p, the last line fails with mkdir: cannot create directory 'project/src/utils': File exists and exit status 1 (the quote characters depend on your locale).

Shell brace expansion can create patterns of names in one command. {a,b,c} expands to three words and {1..5} to five numbers, before touch or mkdir even starts. The details are in Wildcards and Globbing.

Bash Making many files at once

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

You get three report files, five day files (day01.log to day05.log, because the leading zero in 01 makes the shell pad the numbers) and three directories under site.

Writing text with echo and redirection

Without redirection a command writes to the screen. The operator > redirects its output into a file instead: the file is created if needed and replaced (truncated) if it exists. The operator >> appends to the end instead. This is covered fully in Standard Streams and Redirection, but you need the two basics now.

Bash Overwrite with > and append with >>

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The second > throws away first line, which is the most common way to lose data by accident. Use >> when you want to keep what is there. Note also that echo "x" > file creates the file even when the command has nothing to print, so > empty.txt on its own is a legal way to create or truncate a file.

> truncates the file before the command runs. In sort data.txt > data.txt the shell empties data.txt first, so sort reads nothing and you lose your data. Write to a different file, then move it over the original, or use sort -o data.txt data.txt, which is designed for that.

echo or printf?

echo is convenient but not fully predictable: whether it understands -e and escape sequences such as \n depends on the shell and on its settings, and text that begins with a dash can be taken for an option. printf works the same everywhere. It takes a format string, where %s is replaced by the next argument, and the format is reused when there are more arguments than placeholders. It does not add a newline by itself, so you write \n.

Bash printf for predictable output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

printf '%s\n' apple pear fig prints three lines because the format is applied once per argument: this idiom is the cleanest way to print a list, one item per line. The numeric format %5d pads to a width of five, and %-8s left-aligns in eight characters. We use printf rather than echo -e in everything that matters; printf, Dates and Formatting goes deeper.

Multi-line files with here-documents

For several lines, a here-document is easier than many echo commands. Everything between <<EOF and a line containing only EOF is fed to the command as input. Combined with >, it writes a whole file. If you quote the delimiter (<<'EOF'), the shell leaves $variables and backticks in the text alone; if you don't, they are expanded.

Bash Creating a file with a here-document

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

In config.ini the line shows name = Ada, since the delimiter was unquoted and $name was expanded. In the template, $USER stays as typed because of the quoted 'EOF'. Use the quoted form whenever you generate scripts or code, and the unquoted form for templates you want to fill in. The delimiter must be at the very beginning of its line, with no spaces. More variants, such as <<- and here-strings, are in Here-Documents, Here-Strings and Input.

Viewing files

cat (short for "concatenate") prints files to the screen, one after the other, and with several names it joins them. For short files it is all you need. Useful options:

Command Effect
cat file Print the whole file
cat a b c Print several files in a row
cat -n file Number all lines
cat -A file Show invisible characters: tabs as ^I, line ends as $
tac file Print the lines in reverse order

cat -A is a debugging favorite: it reveals trailing spaces, tabs and Windows line endings (^M) that make scripts fail mysteriously. For big files you would use head, tail or a pager such as less; Viewing and Slicing Text covers them.

Bash cat and its useful options

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

In the -A output the second line has ^I where the tab was, and the third line reveals two trailing spaces before the $, which you could never see on a plain listing.

Counting and inspecting: wc, file and stat

wc counts: -l lines, -w words, -c bytes. With no option it prints all three, followed by the name. Reading from standard input instead of a file gives a bare number, which is easier to use in scripts. file looks at the content of a file (not the extension) and says what it is. stat prints the metadata the filesystem keeps: size, type, permissions, links and times. The -c option takes a format, e.g. %s for the size in bytes.

Bash wc, file and stat

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

wc words.txt prints 2 5 24 words.txt: two lines, five words, 24 bytes. The file command recognizes the shebang line in tool.sh and describes it as a Bash script, and reports folder as a directory (our sandbox adds setgid, in front, a permission flag inherited from its parent directory; on your machine you will see just directory). stat -c '%n: %s bytes, %F' produces a custom one-line report. Typical -c fields are %n (name), %s (size), %F (type), %a (permissions in octal) and %y (modification time).

File names with spaces and other surprises

Linux allows spaces, quotes and even newlines in names, but the shell splits words at spaces, so such names need care: put the name in quotes, or escape each space with a backslash. The same applies to variables: always write "$file", never $file (see Quoting and Expansion).

Bash Names with spaces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Both spellings, "my notes.txt" and my\ other\ notes.txt, create one file each. The loop prints each name in brackets so that the spaces are visible, and ${#f} gives the length of the name.

A few naming habits will save you headaches:

  • Use lowercase letters, digits, -, _ and ., and avoid spaces; scripts and teammates will thank you.
  • Never start a name with a dash: -n.txt looks like an option. If you must, write ./-n.txt or put -- before the names.
  • Extensions are only a convention (.txt, .sh), not required, and Linux does not use them to decide how to run a file; the permission bits and the shebang do (Writing Your First Script).
  • Names are case sensitive and can be up to 255 bytes long.

Check your understanding

Quick check ยท 6 questions

of 6 answered You scored / 6 ยท perfect!

  1. 1. What does touch notes.txt do if notes.txt already exists?

    touch creates a missing file but only updates the timestamps of an existing one; the content stays.
  2. 2. Which command appends a line to a file without removing the existing content?

    >> appends; a single > truncates the file first.
  3. 3. What is the advantage of mkdir -p a/b/c?

    -p creates the whole chain and is idempotent, so scripts can run it repeatedly.
  4. 4. In a here-document, how do you stop $USER from being expanded?

    A quoted delimiter turns off expansion inside the here-document, so the text is kept literally.
  5. 5. printf '%s\n' a b c prints:

    printf reuses the format for every extra argument, so each item is printed on its own line.
  6. 6. How can you create a file whose name contains a space?

    Quoting or escaping makes the shell pass the name as a single argument.

Summary

  • touch creates empty files (or updates timestamps), mkdir -p creates nested directories and is safe to repeat; brace expansion builds many names at once.
  • > creates or replaces a file, >> appends; never redirect a file onto its own input.
  • Prefer printf over echo for predictable output; a here-document writes multi-line files, and a quoted delimiter prevents expansion.
  • cat, cat -n, cat -A and tac print files; wc counts lines, words and bytes; file identifies content; stat -c reports metadata.
  • Quote file names with spaces, avoid leading dashes, and prefer simple lowercase names.

Next: Copying, Moving and Deleting