Linux Basics

Directory layout, files and permissions, processes, I/O and redirection, brackets and symbols: the groundwork before the commands. Command links open their detail page in a new tab.

01

Directory layout: what each folder is for

Linux has a single directory tree with everything under the root /. There are no drive letters like C: or D:; USB sticks and extra disks are mounted onto a directory in the tree. What each directory is for is defined by the FHS (Filesystem Hierarchy Standard), which most distributions follow.

Try ls / and tree -L 1 / in the simulator.

Top-level directories

DirectoryNamePurpose
/binbinariesEssential commands for all users, e.g. ls, cp, cat
/sbinsystem binariesSystem administration commands, usually needing root, e.g. fdisk, reboot
/bootbootFiles needed to start the system: the kernel (vmlinuz), initramfs, the GRUB boot loader
/devdevicesDevice files. A disk is /dev/sda; /dev/null is a "black hole" that discards whatever is written to it
/etcOriginally "et cetera" (everything else); often read today as "editable text configuration"System-wide configuration files, e.g. /etc/passwd, /etc/hosts, /etc/nginx/
/homehomeHome directories of regular users, e.g. /home/alice; ~ means your own
/rootrootHome directory of the superuser root (not under /home)
/lib, /lib64librariesShared libraries (like Windows .dll files) for programs in /bin and /sbin, plus kernel modules
/mediamediaRemovable media mounted automatically: USB sticks, CDs
/mntmountWhere an administrator mounts file systems temporarily
/optoptionalSelf-contained third-party software, e.g. /opt/google/chrome
/procprocessesVirtual file system generated live by the kernel: one directory per process (/proc/1234), plus /proc/cpuinfo, /proc/meminfo
/runrun timeRuntime data since boot, such as PID files and sockets; cleared on reboot
/srvservicesData for services this machine provides, e.g. websites, FTP files
/syssystemVirtual file system to inspect and tune the kernel, hardware and drivers
/tmptemporaryTemporary files, writable by everyone, usually cleared on reboot
/usrOriginally user (home directories); often explained as "Unix System Resources"Most installed software and read-only data: /usr/bin, /usr/lib, /usr/share
/varvariableData that changes while the system runs: logs in /var/log, caches in /var/cache, mail, databases

Inside /usr

DirectoryPurpose
/usr/binWhere almost all user commands live
/usr/sbinNon-essential administration commands
/usr/libLibraries
/usr/localSoftware the administrator builds or installs by hand, safe from the package manager; has its own bin, lib …
/usr/shareArchitecture-independent data: documentation, man pages (/usr/share/man), icons
/usr/includeC/C++ header files
Tip

Did you know? Many recent distributions have "merged /usr": /bin, /sbin and /lib are just symbolic links to /usr/bin, /usr/sbin and /usr/lib. Look for the -> arrows in ls -l /.

Where to look

  • Configuration problem? Start with the program's files in /etc.
  • A program is failing? Check the logs in /var/log, or use journalctl.
  • Your own files belong in ~ (your home); no root needed.
  • Quick experiments can go in /tmp.
  • Software you install yourself goes in /opt or /usr/local.
02

Paths and file names

Absolute and relative paths

  • An absolute path starts at the root / and means the same thing wherever you are: /home/user/projects/hello.py
  • A relative path starts from the current directory: if you are in /home/user, then projects/hello.py is the same file

Use pwd to see where you are and cd to move.

Special names

NameMeaningExample
.The current directory./script.sh runs a script in this directory
..The parent directorycd .., cp file ../backup/
~Your home directorycd ~, ls ~/projects
~alicealice's home directoryls ~alice
-(cd only) The previous directorycd -
/The root, and the path separatorcd /

Naming rules

  • Case-sensitive: Notes.txt and notes.txt are different files.
  • Almost any character is allowed, except / (the separator) and the NUL byte. Names are usually limited to 255 bytes.
  • Names starting with . are hidden, e.g. .bashrc, .ssh/. Plain ls skips them; use ls -a.
  • Extensions are only a convention: Linux doesn't use them to decide a file's type (use the file command) or whether it can run (that's the execute permission).
  • Avoid spaces and special characters. If a name has a space, quote it or escape it with a backslash:
bash
cat "my notes.txt"
cat my\ notes.txt

A good habit: lower-case letters, digits, -, _ and ., e.g. backup-2026-01-15.tar.gz.

Wildcards: matching many names at once

The shell expands wildcards into matching file names before the command runs:

WildcardMatchesExample
*Any number of characters (including none)ls *.txt
?Exactly one characterls file?.log matches file1.log, not file10.log
[abc]One of the listed charactersls [abc]*
[0-9]One character in a rangels report[0-9].txt
[!abc]One character not listedls [!.]*

Note: * doesn't match hidden files starting with ., and quoted wildcards are not expanded: in find . -name "*.txt", the pattern *.txt is passed to find unchanged.

03

File types and permissions

Reading ls -l

text
-rwxr-xr-x 1 user user 42 Jan 15 09:30 hello.py

From left to right:

PartExampleMeaning
1st character-File type
Characters 2–4rwxPermissions of the owner (user)
Characters 5–7r-xPermissions of the group
Characters 8–10r-xPermissions of everyone else (others)
Number1Number of hard links
Namesuser userOwner and group
Number42Size in bytes
DateJan 15 09:30Last modification time

The first character: file type

CharacterType
-Regular file
dDirectory
lSymbolic link, like a shortcut
cCharacter device, e.g. a terminal /dev/tty
bBlock device, e.g. a disk /dev/sda
sSocket
pNamed pipe

What rwx means

PermissionOn a fileOn a directory
r readView the contentList the entries
w writeChange the contentCreate, delete and rename entries
x executeRun it as a programEnter it (cd) and access entries inside

Octal notation

Each group of three is one digit: r = 4, w = 2, x = 1, added together.

NumberPermissionsTypical use
755rwxr-xr-xScripts, programs, directories
644rw-r--r--Ordinary files
700rwx------A directory only you can use
600rw-------Private files, e.g. SSH keys

Change permissions with chmod and ownership with chown:

bash
chmod 755 deploy.sh      # octal
chmod u+x deploy.sh      # symbolic: add (+) execute (x) for the owner (u)
chmod go-w notes.txt     # remove write for group (g) and others (o)
sudo chown alice:dev app.py

Users, groups and root

  • Every user has a UID and every group a GID; see them with id.
  • root (UID 0) is the superuser and ignores permissions. Don't work as root day to day; use sudo when you need it.
  • Users are listed in /etc/passwd, groups in /etc/group, and password hashes in /etc/shadow (readable only by root).

Special permissions: setuid, setgid, sticky

Besides rwx there are three special permission bits. You rarely set them, but you meet them all over the system:

BitNumberIn ls -lOn a file (a program)On a directory
setuid4000the owner's x becomes sruns as the file's owner, as passwd doesno effect
setgid2000the group's x becomes sruns with the file's groupfiles created in it get the directory's group
sticky1000the others' x becomes tno effecteveryone may create files, but only delete their own

Some you will see:

  • /usr/bin/passwd is -rwsr-xr-x: when an ordinary user runs passwd, it runs as root, so it can change /etc/shadow, which only root may write.
  • /tmp is drwxrwxrwt: everyone may create files there, but nobody may delete someone else's.
  • A team directory is often 2775 (drwxrwsr-x): new files belong to the team's group, so everyone in it can work on them.

To set them, write one more digit in front (4 setuid, 2 setgid, 1 sticky; they add up), or use s and t:

bash
ls -ld /tmp            # drwxrwxrwt: the t at the end is sticky
chmod 2775 backup      # the leading 2 is setgid; 775 as usual
chmod g+s backup       # the same with letters: setgid for the group
chmod +t backup        # sticky on a directory
chmod u+s hello.sh     # setuid for the owner
find / -perm -4000 -type f 2>/dev/null   # every setuid program on the system

Keep in mind:

  • A capital S or T means the special bit is set but the x under it is not; usually a mistake.
  • A setuid program runs as someone else, so a bug in it can hand out their rights; security checks list them with the find above.
  • Linux ignores setuid on scripts (files starting with #!/bin/bash); it only works on compiled programs.

To try it out, use the chmod permission calculator: tick the bits and see the ls -l form and what each one means.

04

Processes: parents and children

Programs and processes

A program is a file on disk (e.g. /usr/bin/ls); a process is a running instance of a program. The same program can run as several processes at once. Each process has a unique number, its PID (process ID).

bash
ps -ef     # list every process
top        # live view

See ps, top and pstree.

Parent and child processes

Apart from the very first one, every process is created by another process: the creator is the parent, the new one the child. The parent's number is the PPID (parent PID).

  • At boot the kernel starts the process with PID 1 (nowadays usually systemd, formerly init); it is the ancestor of all processes.
  • When you type ls, your shell (e.g. bash) creates a child process to run ls, then waits for the next command once ls finishes.
  • pstree -p shows the whole process tree.

Linux creates a process in two steps:

  1. fork: the parent makes an almost identical copy of itself, the child;
  2. exec: the child replaces itself with the program to run.

What children inherit

A child inherits its parent's environment variables, current directory and open files (including standard input and output). It does not work the other way round: a child cannot change its parent. That explains a common surprise:

bash
bash script.sh      # runs in a child: cd and export inside the script don't affect your shell
source script.sh    # runs in your shell: cd and export take effect

It is also why variables need export: only exported variables are passed to child processes.

Orphans and zombies

  • Orphan: the parent exits while the child keeps running. PID 1 adopts it; usually harmless.
  • Zombie (state Z in ps): the child has finished but the parent hasn't collected its exit status yet, so it still occupies a slot in the process table. A few are fine; many usually point to a bug in the parent.

Foreground, background and signals

ActionEffect
command &Run in the background
Ctrl+CSend SIGINT to the foreground process, usually ending it
Ctrl+ZSuspend the foreground process (SIGTSTP)
jobsList background jobs
fg / bgBring a job to the foreground / continue it in the background
kill PIDSend SIGTERM, asking the process to exit
kill -9 PIDSend SIGKILL, forcing it to stop; it cannot refuse
nohupKeep a command running after you log out

Exit status

Every process returns an exit status when it ends: 0 means success, anything else an error (the program decides what each number means). In the shell, $? holds the status of the last command, and && and || decide based on it:

bash
grep ERROR app.log; echo $?   # 0 if found, 1 if not
mkdir backup && cd backup     # cd only if mkdir succeeded
05

Standard streams and redirection

The three standard streams

Every process starts with three open "files", numbered and called file descriptors:

NumberNameConnected by default toUsed for
0standard input (stdin)keyboardReading input
1standard output (stdout)screenNormal results
2standard error (stderr)screenErrors and warnings

Keeping results and errors apart lets you handle them separately, e.g. save results to a file while errors still show on screen.

Redirection

SyntaxEffect
cmd > fileWrite stdout to a file (overwriting it)
cmd >> fileAppend stdout to a file
cmd < fileRead stdin from a file
cmd 2> fileWrite stderr to a file
cmd 2>> fileAppend stderr to a file
cmd > file 2>&1Send both stdout and stderr to the same file
cmd &> fileShorthand for the above (bash)
cmd > /dev/nullThrow the output away
bash
ls > list.txt                 # save a listing
echo "new line" >> notes.txt  # append a line
sort < names.txt              # read input from a file
find / -name "*.conf" 2> /dev/null   # hide "Permission denied" noise
./build.sh > build.log 2>&1   # keep all output in a log
Important

Order matters: > file 2>&1 means "point stdout at the file, then make stderr follow stdout", so both end up in the file. 2>&1 > file sends only stdout to the file; stderr stays on screen.

Warning

Careful with >: it empties the file immediately. sort file > file leaves you with an empty file, because the shell truncates file before sort even starts.

Pipes |

A pipe connects one command's stdout to the next command's stdin, so small tools combine into powerful ones:

bash
grep ERROR app.log | wc -l
cat access.log | cut -d' ' -f1 | sort | uniq -c | sort -rn | head
ps -ef | grep nginx

Pipes carry only stdout. To send errors down the pipe too, use 2>&1 | (or bash's |&).

To save results and see them at the same time, use tee:

bash
make 2>&1 | tee build.log

Here documents and here strings

Feed several lines of text to a command (the word after << is the end marker; pick any name):

bash
cat > config.ini << END
[server]
port = 8080
END

grep -c a <<< "banana"     # here string: a single string as input

Arguments versus standard input

Some commands take file names as arguments (cat notes.txt), others read standard input (echo hi | cat), and many accept both. When a command only takes arguments but you want to feed it another command's output, use xargs:

bash
find . -name "*.tmp" | xargs rm
06

Brackets, quotes and special characters

The shell has many symbols that look alike; they are where beginners get confused most. Here they are by category.

Brackets

SyntaxNameWhat it doesExample
( cmds )SubshellRuns commands in a child process; cd and variables inside don't leak out(cd /tmp && ls)
{ cmds; }Command groupGroups commands in the current shell (mind the spaces and the final ;){ date; uptime; } > status.txt
$( cmd )Command substitutionRuns a command and puts its output hereecho "Today is $(date +%F)"
`cmd`Command substitution (old style)Same as $( ) but awkward to nest; avoidecho `whoami`
$(( expr ))Arithmetic expansionEvaluates an integer expression and puts the result hereecho $((3 * 4))
(( expr ))Arithmetic commandEvaluates an expression; true when non-zero; used in if and loops(( n > 10 )) && echo big
[ expr ]testTests a condition, same as test; the spaces inside are required[ -f file ] && echo yes
[[ expr ]]Extended test (bash)Safer than [ ]: supports &&, ||, pattern matching and regex =~[[ $name == a* ]]
${var}Parameter expansionA variable's value; braces mark where the name endsecho "${name}_backup"
{a,b,c}Brace expansionGenerates several stringsmkdir {src,docs,tests}
{1..5}Sequence expansionGenerates a run of numbers or lettersecho {1..5}, touch file{a..c}.txt
[abc]Wildcard classMatches one of the listed charactersls [abc]*.txt

Handy parameter expansions

bash
name="report.tar.gz"
echo ${#name}            # length: 13
echo ${name%.gz}         # remove a trailing .gz: report.tar
echo ${name%%.*}         # remove everything from the first dot: report
echo ${name#*.}          # remove up to the first dot: tar.gz
echo ${name/tar/zip}     # replace: report.zip.gz
echo ${user:-guest}      # use guest when user is empty

Three kinds of quotes

QuotesEffectExampleResult
'single'Completely literal; nothing is expandedecho '$HOME'$HOME
"double"Expands variables and command substitution, but no wildcards or word splittingecho "$HOME"/home/user
`backticks`Command substitution (old style)echo `pwd` the current directory

Rule of thumb: almost always put variables in double quotes, "$file", so names with spaces don't break your commands.

Common special characters

SymbolMeaning
$Value of a variable: $HOME, $1
;Run commands one after another, regardless of success
&&Run the next command only if the previous one succeeded
||Run the next command only if the previous one failed
&Run in the background
|Pipe
> >> <Redirection (see the previous section)
\Escape the next character, or continue a command on the next line
#Comment; the rest of the line is ignored
~Home directory
* ?Wildcards
!History (!! is the last command) or negation ([ ! -f file ])

Special variables

VariableMeaning
$?Exit status of the last command
$PID of the current shell
$!PID of the most recent background process
$0Name of the script
$1 … $9Arguments 1 to 9 of a script or function
$#Number of arguments
$@All arguments (as "$@", each stays separate)
07

Variables, environment and PATH

Shell variables

bash
name="Linux"          # assign: no spaces around =
echo "Hello, $name"   # use
unset name            # remove

A variable defined like this exists only in the current shell; child processes can't see it.

Environment variables

After export, a variable becomes an environment variable and is passed to every child process started afterwards:

bash
export EDITOR=vim
env                   # list all environment variables
printenv HOME         # show one

Common environment variables:

VariableMeaning
HOMEYour home directory
USERYour user name
PWDThe current directory
SHELLYour default shell
PATHDirectories searched for commands
LANGLanguage and encoding, e.g. en_US.UTF-8
EDITORYour preferred editor

PATH: how commands are found

When you type ls, the shell looks, in order, for:

  1. an alias (alias);
  2. a shell builtin (such as cd or export);
  3. an executable with that name in each directory listed in PATH, using the first one found.
bash
echo $PATH             # /usr/local/bin:/usr/bin:/bin
which ls               # /usr/bin/ls
type cd                # cd is a shell builtin

See which and type.

The current directory is not in PATH (for security), which is why you run a local script as ./script.sh.

Add your own script directory to PATH:

bash
export PATH="$HOME/bin:$PATH"

Making settings permanent

Variables exported on the command line disappear when you close the terminal. To set them at every login, put them in a startup file:

FileRead when
~/.bashrcEvery new interactive bash (e.g. a new terminal window). Aliases, prompt and PATH usually go here
~/.profile or ~/.bash_profileOnce at login (e.g. over SSH)
/etc/profile, /etc/bash.bashrcFor all users

Run source ~/.bashrc to apply changes right away; see source.

08

Terminal shortcuts

Knowing the shortcuts makes you much faster on the command line. These work in bash and most terminals (the simulator supports most of them).

Editing the command line

ShortcutEffect
TabComplete a command or file name; press twice to list the candidates
Ctrl+A / Ctrl+EJump to the start / end of the line
Ctrl+UDelete everything before the cursor
Ctrl+KDelete everything after the cursor
Ctrl+WDelete the word before the cursor
Alt+B / Alt+FMove back / forward one word

History

ShortcutEffect
↑ / ↓Previous / next command
Ctrl+RSearch history: type a keyword, press Ctrl+R again for older matches
!!Repeat the last command, as in sudo !!
!$The last argument of the previous command

Controlling programs

ShortcutEffect
Ctrl+CInterrupt the running command
Ctrl+ZSuspend the running command (resume with fg)
Ctrl+DEnd of input; on an empty line it exits the shell
Ctrl+LClear the screen, like clear
qQuit full-screen programs such as less, man and top
09

References

To dig deeper, these are the authoritative sources:

In a terminal, man COMMAND and COMMAND --help are always the quickest help.