Linux Command Line Basics Guide
Linux Command Line Basics Guide
[me@linuxbox ~]$
| it's either $ or #
If the last character of the prompt is a pound sign (“#”) rather than a dollar $ ,
the terminal session has superuser privileges.
2. navigation
Understanding the File System Tree
Linux organizes its files in what is called a hierarchical directory structure.
The first directory in the file system is called the root directory.
unlike Windows, which has a separate file system tree for each storage device,
Linux always have a single file system tree, regardless of how many drives or
storage devices are attached to the computer.
Storage devices are attached (or more correctly, mounted) at various points on
the tree according to the whims of the system administrator, the person (or
people) responsible for the maintenance of the system.
navigation commands
pwd print current directory.
ls list the files and directories in the current working directory.
cd change directory .
In the following example, the ls command is given two options, which are the l option
to produce long format output, and the t option to sort the result by the file's
modification time.
[me@linuxbox ~]$ ls -lt
We'll add the long option “--reverse” to reverse the order of the sort.
[me@linuxbox ~]$ ls -lt --reverse
directory description
/ the root directory
/bin Contains binaries (programs) that must be present for the system
to boot and run.
/boot Contains the Linux kernel, initial RAM disk image (for
drivers needed at boot time), and the boot loader.
Interesting files:
● /boot/grub/grub.conf or menu.lst, which
directory description
are used to configure the boot loader.
● /boot/vmlinuz (or something similar), the Linux kernel
/dev This is a special directory that contains device nodes. “Everything
is a file” also applies to devices. Here is where the kernel
maintains a list of all the devices it understands.
/etc The /etc directory contains all of the system-wide
configuration files. It also contains a collection of shell
scripts that start each of the system services at boot time.
Everything in this directory should be readable text.
Interesting files: While everything in /etc is interesting,
here are some all-time favorites:
● /etc/crontab, a file that defines when
automated jobs will run.
● /etc/fstab, a table of storage devices and their
associated mount points.
● /etc/passwd, a list of the user accounts.
/home In normal configurations, each user is given a directory in /home.
Ordinary users can only write files in their home directories. This
limitation protects the system from errant user activity.
/lib Contains shared library files used by the core system programs.
These are similar to dynamic link libraries (DLLs) in Windows.
/lost+found Each formatted partition or device using a Linux file system, such
as ext4, will have this directory. It is used in the case of a partial
recovery from a file system corruption event. Unless something
really bad has happened to our system, this directory will remain
empty.
/media On modern Linux systems the /media directory will contain the
mount points for removable media such as USB drives, CD-
ROMs, etc. that are mounted automatically at insertion.
/mnt On older Linux systems, the /mnt directory contains mount points
for removable devices that have been mounted manually.
/opt The /opt directory is used to install “optional” software. This is
mainly used to hold commercial software products that might be
installed on the system.
/proc The /proc directory is special. It's not a real file system in the
sense of files stored on the hard drive. Rather, it is a virtual file
system maintained by the Linux kernel. The “files” it contains are
directory description
peepholes into the kernel itself. The files are readable and will
give us a picture of how the kernel sees the computer.
/root This is the home directory for the root account.
/sbin This directory contains “system” binaries. These are programs that
perform vital system tasks that are generally reserved for the
superuser.
/tmp The /tmp directory is intended for the storage of temporary,
transient files created by various programs. Some configurations
cause this directory to be emptied each time the system is
rebooted.
/usr The /usr directory tree is likely the largest one on a Linux system.
It contains all the programs and support files used by regular
users.
/usr/bin /usr/bin contains the executable programs installed by the Linux
distribution. It is not uncommon for this directory to hold
thousands of programs.
/usr/lib The shared libraries for the programs in /usr/bin.
/usr/local The /usr/local tree is where programs that are not included with
the distribution but are intended for systemwide use are installed.
Programs compiled from source code are normally installed in
/usr/local/bin. On a newly installed Linux system, this tree exists,
but it will be empty until the system administrator puts something
in it.
/usr/sbin Contains more system administration programs.
/usr/share /usr/share contains all the shared data used by programs in
/usr/bin. This includes things such as default configuration files,
icons, screen backgrounds, sound files, etc
usr/share/doc Most packages installed on the system will include some kind of
documentation. In /usr/share/doc, we will find documentation files
organized by package.
/var With the exception of /tmp and /home, the directories we have
looked at so far remain relatively static, that is, their contents don't
change. The /var directory tree is where data that is likely to
change is stored. Various databases, spool files, user mail, etc.
are located here.
Hard Links
Hard links are the original Unix way of creating links, compared to symbolic
links, which are more modern.
By default, every file has a single hard link that gives the file its name.
When we create a hard link, we create an additional directory entry for a file.
Hard links have two important limitations:
1. A hard link cannot reference a file outside its own file system. This means a link
cannot reference a file that is not on the same disk partition as the link itself.
2. A hard link may not reference a directory.
A hard link is indistinguishable from the file itself. Unlike a symbolic link, when
we list a
directory containing a hard link we will see no special indication of the link.
When a hard link is deleted, the link is removed but the contents of the file itself
continue to exist (that is, its space is not deallocated) until all links to the file are
deleted.
It is important to be aware of hard links because you might encounter them from
time to time, but modern practice prefers symbolic links, .
When thinking about hard links, it is helpful to imagine that files are made up of
two
parts.
In this version of the listing, the first field is the inode number and, as we can
see, both fun and fun-hard share the same inode number, which confirms they
are the same
file.
Symbolic Links
the first letter of the listing is l and the entry seems to have two filenames. This is a
special kind of a file called a symbolic link (also known as a soft link or symlink). In
most Unix-like systems it is possible to have a file referenced by multiple names.
It's important to realise that the first argument after ln -s is stored as the target
of the symlink. It can be any arbitrary string (with the only restrictions that it can't
be empty and can't contain the NUL character), but at the time the symlink
is being used and resolved, that string is understood as a relative
path to the parent directory of the symlink (when it doesn't start
with / ).
so in the above example we can do $ cd foo $ ln -s foo/bar.txt
../bar.txt
One thing to remember about symbolic links is that most file operations are
carried out on the link's target, not the link itself. rm is an exception. When we
delete a link, it is the link that is deleted, not the target.
Wildcards
Using wildcards (which is also known as globbing) allows us to select filenames
based on patterns of characters
wildcard meaning
* Matches any characters
? Matches any single character
[characters] Matches any character that is a member of the set characters
[!characters] Matches any character that is not a member of the set
characters
[[:class:]] Matches any character that is a member of the specified class
character class meaning
[:alnum:] Matches any alphanumeric character
[:alpha:] Matches any alphabetic character
[:digit:] Matches any numeral
[:lower:] Matches any lowercase letter
[:upper:] Matches any uppercase letter
examples
Pattern Matches
g* Any file beginning with g
b*.txt Any file beginning with b followed by .txt
Data??? Any file beginning with Data followed
by exactly three characters
[abc]* Any file beginning with either an a , a
b , or a c
BACKUP.[0-9][0-9][0-9] Any file beginning with BACKUP.
followed by exactly three numerals
[[:upper:]]* Any file beginning with an uppercase letter
[![:digit:]]* Any file not beginning with a numeral
*[[:lower:]123] Any file ending with a lowercase letter or
the numerals “1”, “2”, or “3”
Wildcards can be used with any command that accepts filenames as arguments,
An executable program
A command built into the shell itself.
bash supports a number of commands internally called shell builtins. The cd
command, for example, is a shell builtin.
A shell function.
An alias.
Aliases are commands that we can define ourselves, built from other
commands.
6. I/O Redirection
Standard Input, Output, and Error
Programs send results to standard output (stdout) and error/status messages
to standard error (stderr)
By default, stdout and stderr are linked to the screen, and standard input
(stdin) is linked to the keyboard
Everything is a File
Keeping with the Unix theme, programs treat stdout, stdin, and stderr as files.
Using just the > redirection operator with no command preceding it will truncate
an existing file or create a new empty file.
e.g. > empty.txt
The redirection of stderr must occur after redirecting stdout or it doesn't work
Pipelines |
Connects stdout of one command to stdin of another
e.g. ls /bin /usr/bin | sort
Filters
Pipelines are often used to perform complex operations on data. It is possible to put
several commands together into a pipeline. Frequently, the commands used this way
are referred to as filters. Filters take input, change it somehow, and then output it.
Pathname Expansion
Shell expands wildcards like * into matching filenames before executing
command
e.g. echo * expands to list of files in current directory
Tilde Expansion
~ expands to current user's home directory
~user expands to specified user's home directory
Arithmetic Expansion
Brace Expansion
Parameter Expansion
Command Substitution
Quoting
Double Quotes "
Suppresses word-splitting, pathname, tilde, brace expansions
Allows parameter, arithmetic and command substitutions
Escaping with \
\char escapes special meaning of char
e.g. \$5.00 prints literal $5.00
Key Action
Ctrl-a Move cursor to beginning of line
Ctrl-e Move cursor to end of line
Ctrl-f Move cursor forward one char (right arrow)
Ctrl-b Move cursor backward one char (left arrow)
Alt-f Move cursor forward one word
Alt-b Move cursor backward one word
Ctrl-l Clear screen (same as clear command)
Modifying Text
Key Action
Ctrl-d Delete character at cursor
Ctrl-t Transpose (swap) character at cursor with previous
Alt-t Transpose words at cursor location
Alt-l Convert word at cursor to lowercase
Alt-u Convert word at cursor to uppercase
Key Action
Ctrl-k Kill (cut) text from cursor to end of line
Ctrl-u Kill text from cursor to start of line
Alt-d Kill text from cursor to end of current word
Alt-Backspace Kill text from cursor to start of current word
Ctrl-y Yank (paste) text from kill-ring at cursor
Completion
Pressing Tab attempts to auto-complete current word
Works for paths, variables (start with $), usernames (start with ~ ), hostnames
(start with @), commands
Press Tab twice to see possible completions
Programmable Completion
Allows adding custom completion rules using shell functions, often done by
distro providers
Using History
bash maintains a history of commands that have been entered. This list of
commands is kept in our home directory in a file called .bash_history .
Viewing History
Searching History
history | grep pattern searches for pattern
Can use !n to execute command #n from history
Ctrl-r begins incremental reverse search
Ctrl-r again finds next match
Ctrl-j copies match to command line
History Expansion
Other
script command records entire terminal session to file
9. permissions
Here are extensive notes on the provided content using markdown language:
Unix/Linux Permissions and Access Control
Multi-User Systems
User Identity
$ id
uid=1000(username) gid=1000(username)
groups=1000(username),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),11
3(lpadmin),128(sambashare)
This shows the user's UID, primary GID, and supplementary groups they belong
to
User account information is stored in /etc/passwd
Group information is stored in /etc/group or we can use getent getent group
System Users
Besides regular user accounts, there are also system users for various services
and processes
File Permissions
File permissions control who can read, write, and execute files
Permissions are set for three categories: owner, group, and others
Basic permission types:
Read (r)
Write (w)
Execute (x)
Viewing Permissions
$ ls -l file.txt
-rw-rw-r-- 1 user group 0 Mar 6 14:52 file.txt
Changing Permissions
Octal Notation
Uses 3 octal digits to represent permissions for owner, group, and others
Each digit is the sum of:
4 (read)
2 (write)
1 (execute)
Example:
chmod 644 file.txt
Symbolic Notation
Example:
Adds execute for owner, removes write for group and others
Special Permissions
Default Permissions
The umask command sets default permissions for new files/directories
It specifies which permissions to remove from the default (666 for files, 777 for
directories)
Example:
umask 022
This results in 644 (rw-r--r--) for new files and 755 (rwxr-xr-x) for new directories
Changing Identities
Three ways to change user identity:
su Command
Example:
su -
sudo Command
sudo command
sudo vs su
sudo doesn't start a new shell or load the target user's environment, unlike su
chown Command
Example:
chgrp Command
Changing Passwords
Use the passwd command to change passwords
Without arguments, changes current user's password
Superusers can change other users' passwords: sudo passwd username
Password Policies
Example:
useradd
Low-level command for creating user accounts
Provides more fine-grained control over account creation
Doesn't create home directory by default (use -m option)
groupadd
Creates a new group on the system
Useful for organizing users with similar access needs
Example:
10. Processes
How Processes Work
Linux uses processes to manage programs waiting for CPU time
Kernel initiates a few processes and launches init
init runs scripts to start system services
Many services run as daemon programs in the background
Parent processes can produce child processes
Kernel tracks information about each process:
Process ID (PID)
Memory usage
Readiness to execute
Owner and user IDs
Viewing Processes
Using ps Command
Basic usage: ps
Shows processes associated with current terminal session
Options:
x (not -x) : Show all processes owned by user
aux : Show processes for all users
ps Output
The output includes fields like PID, TTY, TIME, and CMD
top Navigation
Controlling Processes
Background and Foreground
Run a process in background: command &
List background jobs: jobs
Bring a background process to foreground fg: fg %job_number
Send a foreground process to background:
1. Suspend with Ctrl-z
2. Resume in background with bg bg %job_number
Signals
Operating system communicates with programs using signals
Common signals:
SIGHUP (1): Hangup
SIGINT (2): Interrupt (Ctrl-c)
SIGKILL (9): Force termination
SIGTERM (15): Terminate gracefully
SIGCONT (18): Continue after stop
SIGSTOP (19): Stop process
SIGTSTP (20): Terminal stop (Ctrl-z)
Sending Signals
Use kill command: kill [-signal] PID
Send to multiple processes: killall [-u user] [-signal] name
SIGKILL Usage
SIGKILL (9) should be used as a last resort as it doesn't allow the process to
clean up
System Shutdown
Commands: halt , poweroff , reboot , shutdown
shutdown allows specifying action and delay
Command line tools are preferred for process management due to their speed
and low resource usage
File Contents
/etc/profile Global configuration for all users
~/.bash_profile User's personal startup file
~/.bash_login Read if ~/.bash_profile not found
~/.profile Read if neither ~/.bash_profile nor ~/.bash_login found
File Contents
/etc/bash.bashrc Global configuration for all users
~/.bashrc User's personal startup file
Non-login shells inherit the environment from their parent process, usually a
login shell.
Modifying the Environment
Which Files to Modify
System-wide Changes
Only modify files in /etc if you are the system administrator and need to change
defaults for all users.
Always add comments to explain your modifications. This helps you remember
the purpose of changes in the future.
Activating Changes
Changes to .bashrc won't take effect until:
Here are extensive notes on the vi text editor using markdown language, based on
the provided document:
POSIX Requirement
Background
Created in 1976 by Bill Joy
Name derives from "visual" editor (vs. line editors)
Most Linux distributions use vim (Vi IMproved) by Bram Moolenaar
Starting and Stopping vi
Start: vi [filename]
Exit:
:q (quit)
:q! (quit without saving)
Lost in vi?
Editing Modes
1. Command Mode: Default mode, keys are commands
2. Insert Mode: For entering text
Enter: Press i
Exit: Press Esc
Basic Commands
Saving Work
Cursor Movement
Command Prefixes
Many vi commands can be prefixed with a number to repeat the action (e.g., 5j
moves down 5 lines)
Editing Text
Command Action
i Insert at cursor
A Append at end of line
o Open line below cursor
O Open line above cursor
x Delete character at cursor
dd Delete current line
yy Yank (copy) current line
p Paste after cursor
P Paste before cursor
u Undo last change
Unsaved Changes
vi prevents switching files with unsaved changes. Use ! to force (e.g., :bn! )
Summing Up
Learning vi/vim is a valuable skill for Linux users. Its influence extends to many other
Unix programs, making the time investment worthwhile.
Practice
Regular use of vi will help solidify your skills and increase efficiency over time
Here are extensive notes on the chapter about customizing the shell prompt, using
markdown language:
PS1 Variable
ps1_old="$PS1"
PS1="$ps1_old"
Experiment
Text Colors
Background Colors
Color Reset
Always end colored prompts with \[\033[0m\] to reset text color for user input
PS1="\[\033[s\033[0;0H\033[0;41m\033[K\033[1;33m\t\033[0m\033[u\]
<\u@\h \W>\$ "
Compatibility
Some terminal emulators may not support all cursor movement codes
Example:
PS1="\[\033[s\033[0;0H\033[0;41m\033[K\033[1;33m\t\033[0m\033[u\]
<\u@\h \W>\$ "
export PS1
Further Reading
Bash Prompt HOWTO: http://tldp.org/HOWTO/Bash-Prompt-HOWTO/
ANSI Escape Codes: http://en.wikipedia.org/wiki/ANSI_escape_code
Experimentation
Customizing the prompt can be a fun way to personalize your shell experience
and potentially increase productivity
Sure, I'll create extensive notes using markdown language, including the requested
notations for notes, tips, and warnings. I'll use ## for the biggest titles and include all
tables from the document. Here are the notes:
Repositories
Central locations containing thousands of packages
Different repositories for various stages of software development (e.g., testing,
development)
Third-party repositories for legally restricted software
Third-party Repositories
These are often needed for software that can't be included in main distributions
due to legal reasons, such as encrypted DVD support in the US.
Dependencies
Style Command(s)
Debian apt-get update
apt-cache search search_string
Red Hat yum search search_string
Style Command(s)
Debian apt-get update
apt-get install package_name
Red Hat yum install package_name
Style Command(s)
Debian dpkg -i package_file
Red Hat rpm -i package_file
Dependency Resolution
Using low-level tools like rpm doesn't perform dependency resolution. If there
are missing dependencies, the installation will fail.
Removing a Package
Style Command(s)
Debian apt-get remove package_name
Red Hat yum erase package_name
Style Command(s)
Debian apt-get update; apt-get upgrade
Red Hat yum update
Style Command(s)
Debian dpkg -i package_file
Red Hat rpm -U package_file
Debian Upgrade
Style Command(s)
Debian dpkg -l
Red Hat rpm -qa
Determining Whether a Package is Installed
Style Command(s)
Debian dpkg -s package_name
Red Hat rpm -q package_name
Style Command(s)
Debian apt-cache show package_name
Red Hat yum info package_name
Style Command(s)
Debian dpkg -S file_name
Red Hat rpm -qf file_name
Important Commands:
mount - Mount a file system
umount - Unmount a file system
fsck - Check and repair a file system
fdisk - Manipulate disk partition table
mkfs - Create a file system
dd - Convert and copy a file
genisoimage (formerly mkisofs ) - Create an ISO 9660 image file
wodim (formerly cdrecord ) - Write data to optical storage media
md5sum - Calculate an MD5 checksum
Fields in /etc/fstab :
Device Naming
Modern Linux distributions often use labels or UUIDs instead of device files in
/etc/fstab for more reliable mounting
Viewing Mounted File Systems
Use the mount command without arguments:
mount
Output format:
device on mount_point type filesystem_type (options)
Unmounting
Use the umount command:
umount /dev/sdc
Busy Devices
Importance of Unmounting
Unmounting ensures all data is written to the device before removal, preventing
file system corruption.
Determining Device Names
Device files are located in /dev directory
Common naming patterns:
Data Loss
Be extremely careful when using fdisk. Specifying the wrong device can result in
data loss.
Replace ext4 with desired file system type (e.g. vfat for FAT32)
Recovered Files
Recovered file fragments are placed in the lost+found directory of the file system
Examples:
Destructive Command
Double-check input and output specifications when using dd to avoid data loss
dd if=/dev/cdrom of=ubuntu.iso
mkdir /mnt/iso_image
mount -t iso9660 -o loop image.iso /mnt/iso_image
Common options:
md5sum image.iso
md5sum /dev/cdrom
Here are extensive notes on the networking chapter, using markdown and the
requested note/tip/warning formatting:
Background Knowledge
IP addresses
Host and domain names
Uniform Resource Identifiers (URIs)
Installing Commands
Example output:
Network Performance
It's possible to configure network devices to ignore ICMP packets for security
reasons. Firewalls may also block ICMP traffic.
traceroute
Lists all "hops" network traffic takes to reach specified host
Some systems use similar tracepath program instead
Usage: traceroute hostname
Example output:
ip
Multi-purpose network configuration tool
Uses full range of networking features in modern Linux kernels
Replaces deprecated ifconfig program
Can examine network interfaces and routing table
Usage: ip a (to show network interfaces)
Example output:
[me@linuxbox ~]$ ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN
group default
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast
state UP group default qlen 1000
link/ether ac:22:0b:52:cf:84 brd ff:ff:ff:ff:ff:ff
inet 192.168.1.14/24 brd 192.168.1.255 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::ae22:bff:fe52:cf84/64 scope link
valid_lft forever preferred_lft forever
Look for "UP" in the first line for each interface (indicates enabled)
Check for valid IP address in "inet" field
For DHCP systems, a valid IP here verifies DHCP is working
netstat
Example session:
Command Meaning
ftp fileserver Connect to FTP server
anonymous Login name for anonymous access
cd directory Change directory on remote system
ls List directory on remote system
lcd directory Change directory on local system
get file Transfer file from remote to local system
bye Log off and end FTP session
FTP Help
wget
Popular command-line program for file downloading
Works with both web and FTP sites
Can download single files, multiple files, or entire sites
Usage: wget URL
Example:
wget Features
Recursive downloading
Background downloading (continue after logging off)
Resuming partially downloaded files
SSH Tunneling
X11 Forwarding
You may need to use -Y instead of -X on some systems for X11 forwarding
Example session:
[me@linuxbox ~]$ sftp remote-sys
Connecting to remote-sys...
me@remote-sys's password:
sftp> ls
ubuntu-8.04-desktop-i386.iso
sftp> lcd Desktop
sftp> get ubuntu-8.04-desktop-i386.iso
Fetching /home/me/ubuntu-8.04-desktop-i386.iso to ubuntu-8.04-desktop-
i386.iso
/home/me/ubuntu-8.04-desktop-i386.iso 100% 699MB 7.4MB/s 01:35
sftp> bye
Many graphical file managers in Linux support SFTP. You can often use
sftp:// URIs in GNOME or KDE file managers to access remote files securely.
locate variants
Basic Usage:
find directory
Tests
Used to filter results based on criteria
Common file type tests:
Type Description
b Block special device file
c Character special device file
d Directory
f Regular file
l Symbolic link
Example using file type and size tests:
Size Units
Common Tests
Test Description
-cmin n Modified n minutes ago
-cnewer file Modified more recently than file
-ctime n Modified n*24 hours ago
-empty Match empty files/directories
-group name Belonging to group
-iname pattern Case-insensitive name match
-inum n Match inode number
-mmin n Contents modified n minutes ago
-mtime n Contents modified n*24 hours ago
-name pattern Match name pattern
-newer file Modified more recently than file
-nouser No valid owner
-nogroup No valid group
-perm mode Match permissions
-samefile name Same inode as file
-size n Match size
-type c Match file type
Test Description
-user name Belonging to user
Operators
Used to create more complex logical expressions:
Operator Description
-and Both tests true (default, can use -a)
-or Either test true (can use -o)
-not Test is false (can use !)
() Group tests and operators
Escaping Parentheses
find ~ \( -type f -not -perm 0600 \) -or \( -type d -not -perm 0700
\)
Predefined Actions
Action Description
-delete Delete matching files
-ls Perform ls -dils on matches
-print Output full pathname (default)
-quit Quit after first match
Using -delete
Use extreme caution with -delete action
Always test first by replacing with -print
User-Defined Actions
Use -exec to specify custom commands
Format: -exec command {} ;
Use -ok for interactive prompting before execution
Example:
Improving Efficiency
1. Use + instead of ; with -exec to combine results:
Use -print0 with find and --null with xargs to handle filenames containing spaces:
Options
Control the scope of find searches:
Option Description
-depth Process files before directories
-maxdepth levels Set maximum directory depth
-mindepth levels Set minimum directory depth
-mount Don't traverse mounted filesystems
-noleaf Don't optimize for Unix-like filesystems
Here are extensive notes on the provided content using markdown language:
Archiving Programs
tar: Tape archiving utility
zip: Package and compress files
Compressing Files
Data compression removes redundancy from data
Compression algorithms fall into two categories:
Lossless: Preserves all original data
Lossy: Removes some data to allow more compression
Compression Example
gzip
Replaces original file with compressed version
gunzip restores compressed files
Basic usage:
gzip foo.txt
gunzip foo.txt.gz
Key options:
bzip2
Similar to gzip but uses different algorithm
Achieves higher compression at cost of speed
Uses .bz2 extension
bunzip2 for decompression
bzcat to view contents
Archiving Files
tar
Classic Unix archiving tool
Name means "tape archive"
Can archive files, directories, or both
Basic syntax:
Common modes:
Mode Description
c Create archive
x Extract archive
r Append to archive
t List contents of archive
Example usage:
Compression options:
Basic usage:
unzip -l playground.zip
unzip playground.zip playground/dir-087/file-Z
Basic syntax:
rsync options source destination
Example usage:
A trailing slash on the source copies only contents, not the directory itself
Network usage:
1. With SSH:
Here are extensive notes on the Regular Expressions chapter, using Markdown
formatting:
Key Concepts
Regular expressions allow matching and manipulating text patterns
They use special metacharacters to define patterns
POSIX standard defines Basic (BRE) and Extended (ERE) regular expression
syntax
Many Unix/Linux tools support regular expressions, including grep, sed, awk
Option Description
-i Ignore case
-v Invert match - print non-matching lines
Option Description
-c Print count of matching lines
-l Print names of files with matches
-n Prefix output with line numbers
-h Suppress filenames in multi-file searches
Escaping Metacharacters
Examples:
Character Classes
POSIX defines standard character classes to match sets of characters:
Class Description
[:alnum:] Alphanumeric characters
[:alpha:] Alphabetic characters
[:digit:] Digits
[:lower:] Lowercase letters
[:upper:] Uppercase letters
[:punct:] Punctuation characters
[:space:] Whitespace characters
Example:
| - Alternation (OR)
( ) - Grouping
? - Match 0 or 1 occurrence
Match 0 or more occurrences
Match 1 or more occurrences
{ } - Match specific number of occurrences
Example:
? - Match 0 or 1 time
Match 0 or more times
Match 1 or more times
{n} - Match exactly n times
{n,} - Match n or more times
{n,m} - Match between n and m times
Example:
This will print lines that don't match the phone number pattern.
vim Regex
vim uses basic regex by default. Escape special chars like: (..) {3}
nl - Number lines
fold - Wrap lines to a specified length
fmt - Simple text formatter
pr - Prepare text for printing
printf - Format and print data
groff - Document formatting system
Common options:
Option Meaning
-b style Set body numbering style
-f style Set footer numbering style
-h style Set header numbering style
-i number Set page numbering increment
-n format Set numbering format
-p Don't reset numbering at start of page
-s string Add separator after line numbers
-v number Set first line number
-w width Set width of line number field
Example usage:
This sorts the distros.txt file, processes it with a sed script to add markup, then
numbers the lines with nl.
echo "The quick brown fox jumped over the lazy dog." | fold -w 12
echo "The quick brown fox jumped over the lazy dog." | fold -w 12 -s
Example:
fmt -w 50 -c file.txt
Useful options:
Option Description
-c Preserve indentation of first two lines
-p string Only format lines beginning with prefix
-s Split lines only, don't join short lines
-u Do uniform spacing (1 space between words, 2 after sentences)
This will format only the lines starting with "# " while leaving code untouched.
Example:
pr -l 15 -w 65 distros.txt
Specifier Description
d Signed decimal integer
f Floating point number
o Octal number
s String
x Lowercase hexadecimal
X Uppercase hexadecimal
%[flags][width][.precision]conversion_specification
Flags:
Flag Description
# Use "alternate format"
0 Pad with zeros
- Left-align
'' Add space before positive numbers
+ Always show sign for numbers
Examples:
printf vs echo
While echo is simpler, printf offers much more control over formatting output,
making it very useful in scripts that need to produce precisely formatted text.
groff
GNU implementation of troff
Uses markup language to describe formatting
Often used with macro packages for easier formatting
Converting to PDF
Many command line tools exist for file format conversion, often named
format2format or formattoformat.
22. printing
A Brief History of Printing in Unix-like Systems
Early Days of Printing
Printers were large, expensive, and centralized in the pre-PC era
Users shared printers, with banner pages identifying print jobs
Printers used impact technology (e.g. daisy-wheel, dot-matrix)
Character-based printers used fixed character sets
Monospaced fonts were standard
Standard page size: 80 characters wide, 66 lines high
Monospaced Fonts
Monospaced fonts have fixed character widths, allowing for predictable page
layouts.
Printing Process
Data sent as simple byte stream of characters
ASCII control codes used for carriage control
Special effects like boldface achieved through overprinting
N^HNA^HAM^HME^HE
PostScript allowed for complex layouts and font support while reducing data
transmission needs.
Common pr options:
Option Description
+first[:last] Output a range of pages
-columns Organize content into specified number of columns
Option Description
-a List content horizontally in multi-column output
-d Double-space output
-D "format" Format the date in page headers
-f Use form feeds to separate pages
-h "header" Set custom page header
-l length Set page length (default: 66)
-n Number lines
-o offset Create left margin
-w width Set page width (default: 72)
Example usage:
ls /usr/bin | pr -3 -w 65 | head
Example:
ls /usr/bin | pr -3 | lpr
Common lp options:
Option Description
-d printer Set destination printer
-n number Set number of copies
-o landscape Set landscape orientation
-o fitplot Scale file to fit page
-o scaling=number Scale file (100 fills page)
-o cpi=number Set characters per inch
-o lpi=number Set lines per inch
-o page-*=points Set page margins
-P pages Specify pages to print
a2ps Output
a2ps typically produces "two up" format, printing two pages per sheet with
headers and footers.
Option Description
--center-title=text Set center page title
--columns=number Arrange pages into columns
--footer=text Set page footer
--guess Report file types
--line-numbers=interval Number lines of output
--pages=range Print specific page range
-B No page headers
-f size Set font size
-l number Set characters per line
-L number Set lines per page
-M name Use specific media type
-o file Send output to file
-P printer Specify printer
-R Portrait orientation
-r Landscape orientation
Alternative to a2ps
Option Description
-a [printer...] Display printer queue state
-d Show default printer
-p [printer...] Display printer status
-r Show print server status
-s Display status summary
-t Show complete status report
Example:
lpq
Example:
cancel 603
Job Cancellation
Make sure to use the correct job ID when cancelling print jobs to avoid affecting
other users' prints.
These commands provide comprehensive control over the printing process in Unix-
like systems, from formatting and sending print jobs to managing printer queues and
cancelling jobs when needed.
Here are extensive notes on the chapter about compiling programs, using markdown
formatting:
Distribution Repositories
What is Compiling?
Compiling is the process of translating human-readable source code into machine
language that can be executed by the computer's processor.
Key points:
Some languages like Python and Ruby are interpreted rather than compiled. An
interpreter executes the code directly, which is slower but allows for faster
development cycles.
Compiling a C Program
Steps to compile a C program:
mkdir src
cd src
ftp ftp.gnu.org
ftp> cd gnu/diction
ftp> get diction-1.11.tar.gz
ftp> bye
wget https://ftp.gnu.org/gnu/diction/diction-1.11.tar.gz
Makefile
Key Commands
configure - Analyzes build environment and creates Makefile
make - Compiles the program based on the Makefile
make install - Installs the compiled program
#!/bin/bash
# This is a comment
echo 'Hello World!'
Shebang
The first line #!/bin/bash is called a shebang. It tells the system to use bash to
interpret the script.
./script_name
Place scripts in a directory in your PATH (like ~/bin) so they can be run from
anywhere
export PATH=~/bin:"$PATH"
find playground \
\( \
-type f \
-not -perm 0600 \
-exec chmod 0600 '{}' ';' \
\) \
-or \
\( \
-type d \
-not -perm 0700 \
-exec chmod 0700 '{}' ';' \
\)
Shell Functions
"Mini-scripts" inside other scripts
Act as autonomous programs
Two syntactic forms:
function name {
commands
return
}
# Or
name () {
commands
return
}
Function definitions must appear before they are called in the script
Local Variables
Accessible only within the shell function where defined
Cease to exist once the function terminates
Defined using the local keyword:
local variable_name
Variable Scope
Local variables are only visible within the function where they are defined.
Global variables are visible throughout the entire script.
report_uptime () {
echo "Function report_uptime executed."
return
}
ds () {
echo "Disk Space Utilization For $HOSTNAME"
df -h
}
#!/bin/bash
report_uptime () {
return
}
report_disk_space () {
return
}
report_home_space () {
return
}
Implementing Functions
Example implementation of report_uptime :
report_uptime () {
cat <<- _EOF_
<h2>System Uptime</h2>
<pre>$(uptime)</pre>
_EOF_
return
}
Here Documents
Embed multi-line text directly in scripts
Syntax:
Use <<- instead of << to allow indentation with tabs (not spaces) in the here
document.
By following these practices and structuring scripts using functions and top-down
design, you can create more maintainable and readable shell scripts.
if commands; then
commands
[elif commands; then
commands...]
[else
commands]
fi
Evaluation
The if statement evaluates the exit status of commands. A zero exit status
means success/true, while non-zero means failure/false.
Exit Status
Commands issue an exit status (0-255) when they terminate
0 indicates success, any other value indicates failure
The $? variable holds the exit status of the last executed command
Example:
ls -d /usr/bin
echo $? # Outputs 0 (success)
ls -d /bin/usr
echo $? # Outputs non-zero (failure)
The true command always exits with status 0, while false always exits with
status 1. These can be used to test if statement behavior.
test expression
[ expression ]
Command Nature
Both test and [ are actually commands, with [ requiring ] as its final
argument.
File Expressions
String Expressions
String Comparisons
The > and < operators must be quoted or escaped when used with test to
prevent shell interpretation as redirection operators.
Integer Expressions
Combining Expressions
Logical operators can combine expressions:
Preference
These are useful for simple conditionals and error handling in scripts.
Portability
While portability to all Unix-like systems is sometimes emphasized, using bash-
specific features can lead to more readable and maintainable scripts, especially
since bash is widely available.
Here are extensive and understandable notes on the content using markdown:
Multiple Variables
If fewer values are input than variables specified, extra variables are empty. If
more values are input, the final variable contains all extra input.
#!/bin/bash
echo -n "Please enter an integer -> "
read int
read Options
Option Description
-a array Assign input to array, starting with index zero
-d delimiter Use first character of delimiter string to indicate end of input
-e Use Readline to handle input, allowing editing
-i string Use string as default reply if user presses Enter (requires -e)
-n num Read num characters of input instead of entire line
-p prompt Display prompt string for input
-r Raw mode - don't interpret backslashes as escapes
-s Silent mode - don't echo characters (useful for passwords)
-t seconds Timeout after specified seconds
-u fd Use input from file descriptor fd instead of standard input
IFS=":" read user pw uid gid name home shell <<< "$file_info"
Here Strings
Use <<< operator to provide a string as input to a command:
Piping to read
Validating Input
Always validate user input to handle unexpected or malicious data. Example:
#!/bin/bash
invalid_input () {
echo "Invalid input '$REPLY'" >&2
exit 1
}
Menu-Driven Programs
Create interactive menus for user selection:
#!/bin/bash
clear
echo "
Please Select:
1. Display System Information
2. Display Disk Space
3. Display Home Space Utilization
0. Quit
"
read -p "Enter selection [0-3] > "
Exit Points
Multiple exit points in a program can make logic harder to follow, but work well in
menu-driven scripts.
while commands; do
commands
done
Loop Execution
User Experience
Adding a pause with sleep allows users to see results before the screen clears
for the next menu display.
Endless Loop
Using while true creates an endless loop. The programmer must provide a
way to exit, typically with break.
#!/bin/bash
# until-count: display a series of numbers
count=1
until [[ "$count" -gt 5 ]]; do
echo "$count"
count=$((count + 1))
done
echo "Finished."
Select the loop type that allows for the clearest test expression to be written.
#!/bin/bash
# while-read: read lines from a file
while read distro version release; do
printf "Distro: %s\tVersion: %s\tReleased: %s\n" \
"$distro" \
"$version" \
"$release"
done < distros.txt
File Redirection
The redirection operator < distros.txt is placed after the done statement to
feed the file into the loop.
Subshell Limitation
When using a pipe to feed a loop, the loop executes in a subshell. Variables
created or modified within the loop are lost when the loop terminates.
Summary
Loops are essential for repeated tasks in shell scripts
while and until provide flexible looping constructs
break and continue offer additional loop control
Loops can process files and piped input efficiently
Further Learning
Explore more complex loop structures and combine them with other flow control
techniques for advanced scripting capabilities.
#!/bin/bash
number=1
if [ $number = 1 ]; then
echo "Number is equal to 1.
else
echo "Number is not equal to 1."
fi
Result:
Quote Errors
Missing Tokens
#!/bin/bash
number=1
if [ $number = 1 ] then
echo "Number is equal to 1."
else
echo "Number is not equal to 1."
fi
Result:
Missing Semicolon
Unanticipated Expansions
#!/bin/bash
number=
if [ $number = 1 ]; then
echo "Number is equal to 1."
else
echo "Number is not equal to 1."
fi
Result:
if [ "$number" = 1 ]; then
Defensive Programming
Verify assumptions
Check exit status of commands
Validate input
Handle potential errors
Dangerous Filenames
Unix allows almost any character in filenames, including spaces and hyphens.
Use ./ before wildcards to prevent misinterpretation:
rm ./*
Testing
Release early and often for more exposure
Use stubs to verify program flow
Develop good test cases covering edge conditions
Test coverage should reflect importance of functionality
Debugging Techniques
1. Isolate problem area by commenting out sections
2. Add tracing messages
3. Use bash's built-in tracing
4. Examine variable values during execution
Tracing
Add messages:
#!/bin/bash -x
Examining Values
Add debug echo statements:
number=1
echo "number=$number" # DEBUG
Debugging is an Art
Developed through experience
Involves knowing how to avoid bugs
Requires effective use of tracing and testing
Here are extensive markdown notes on the provided content about flow control and
branching with the case command in bash:
Syntax of case
case word in
[pattern [| pattern]...) commands ;;]...
esac
Syntax Explanation
clear
echo "
Please Select:
1. Display System Information
2. Display Disk Space
3. Display Home Space Utilization
0. Quit
"
read -p "Enter selection [0-3] > "
#!/bin/bash
# case-menu: a menu driven system information program
clear
echo "
Please Select:
1. Display System Information
2. Display Disk Space
3. Display Home Space Utilization
0. Quit
"
read -p "Enter selection [0-3] > "
case "$REPLY" in
0) echo "Program terminated."
exit
;;
1) echo "Hostname: $HOSTNAME"
uptime
;;
2) df -h
;;
3) if [[ "$(id -u)" -eq 0 ]]; then
echo "Home Space Utilization (All Users)"
du -sh /home/*
else
echo "Home Space Utilization ($USER)"
du -sh "$HOME"
fi
;;
*) echo "Invalid entry" >&2
exit 1
;;
esac
Simplification
Using case simplifies the logic and makes the code more readable compared to
multiple if statements.
Patterns in case
Patterns in case are similar to those used in pathname expansion
Patterns are terminated with a ) character
Pattern Description
a) Matches if word equals "a"
:alpha:) Matches if word is a single alphabetic character
???) Matches if word is exactly three characters long
*.txt) Matches if word ends with the characters ".txt"
*) Matches any value of word (catch-all)
Catch-all Pattern
It's good practice to include *) as the last pattern to catch any invalid values.
Example of Patterns:
#!/bin/bash
read -p "enter word > "
case "$REPLY" in
[[:alpha:]]) echo "is a single alphabetic character." ;;
[ABC][0-9]) echo "is A, B, or C followed by a digit." ;;
???) echo "is three characters long." ;;
*.txt) echo "is a word ending in '.txt'" ;;
*) echo "is something else." ;;
esac
Combining Multiple Patterns
Use | (vertical bar) to separate multiple patterns
Creates an "or" conditional pattern
Useful for handling both uppercase and lowercase characters
#!/bin/bash
# case-menu: a menu driven system information program
clear
echo "
Please Select:
A. Display System Information
B. Display Disk Space
C. Display Home Space Utilization
Q. Quit
"
read -p "Enter selection [A, B, C or Q] > "
case "$REPLY" in
q|Q) echo "Program terminated."
exit
;;
a|A) echo "Hostname: $HOSTNAME"
uptime
;;
b|B) df -h
;;
c|C) if [[ "$(id -u)" -eq 0 ]]; then
echo "Home Space Utilization (All Users)"
du -sh /home/*
else
echo "Home Space Utilization ($USER)"
du -sh "$HOME"
fi
;;
*) echo "Invalid entry" >&2
exit 1
;;
esac
#!/bin/bash
# case4-2: test a character
read -n 1 -p "Type a character > "
echo
case "$REPLY" in
[[:upper:]]) echo "'$REPLY' is upper case." ;;&
[[:lower:]]) echo "'$REPLY' is lower case." ;;&
[[:alpha:]]) echo "'$REPLY' is alphabetic." ;;&
[[:digit:]]) echo "'$REPLY' is a digit." ;;&
[[:graph:]]) echo "'$REPLY' is a visible character." ;;&
[[:punct:]]) echo "'$REPLY' is a punctuation symbol." ;;&
[[:space:]]) echo "'$REPLY' is a whitespace character." ;;&
[[:xdigit:]]) echo "'$REPLY' is a hexadecimal digit." ;;&
esac
Multiple Matches
The ;;& syntax allows case to continue to the next test rather than terminating
after the first match.
Summary
case is a powerful tool for handling multiple-choice decisions in bash scripts
It offers a cleaner alternative to multiple if statements
Pattern matching in case is versatile and can handle various scenarios
bash 4.0+ enhances case with the ability to perform multiple actions on a single
match
Best Practice
Use case when dealing with multiple conditions that can be expressed as
patterns, especially for menu-driven programs or command-line argument
parsing.
Further Reading
Bash Reference Manual on Conditional Constructs:
http://tiswww.case.edu/php/chet/bash/bashref.html#SEC21
Advanced Bash-Scripting Guide examples:
http://tldp.org/LDP/abs/html/testbranch.html
Here are extensive and understandable notes on the content using markdown:
Example script:
#!/bin/bash
echo "
\$0 = $0
\$1 = $1
\$2 = $2
...
\$9 = $9
"
Example:
Example:
#!/bin/bash
PROGNAME="$(basename "$0")"
if [[ -e "$1" ]]; then
echo -e "\nFile Type:"
file "$1"
echo -e "\nFile Status:"
stat "$1"
else
echo "$PROGNAME: usage: $PROGNAME file" >&2
exit 1
fi
Using basename
basename removes the path from $0, leaving just the script name
Parameter Description
$* Expands to all parameters as a single string
$@ Expands to all parameters as separate strings
Using "$@"
"$@" is usually the safest way to handle all parameters, as it preserves spaces
in individual arguments
touch and test combination ensures the file is writable and a regular file
Here are extensive and understandable notes on the content using markdown
language:
Example:
Output:
A
B
C
D
There are several ways to generate the list of words for the loop:
for i in distros*.txt; do
if [[ -e "$i" ]]; then
echo "$i"
fi
done
2. C Language Form
Syntax:
Example:
Output:
0
1
2
3
4
Practical Examples
1. Finding the Longest String in a File
#!/bin/bash
# longest-word: find longest string in a file
while [[ -n "$1" ]]; do
if [[ -r "$1" ]]; then
max_word=
max_len=0
for i in $(strings "$1"); do
len="$(echo -n "$i" | wc -c)"
if (( len > max_len )); then
max_len="$len"
max_word="$i"
fi
done
echo "$1: '$max_word' ($max_len characters)"
fi
shift
done
Word Splitting
#!/bin/bash
# longest-word2: find longest string in a file
for i; do
if [[ -r "$i" ]]; then
max_word=
max_len=0
for j in $(strings "$i"); do
len="$(echo -n "$j" | wc -c)"
if (( len > max_len )); then
max_len="$len"
max_word="$j"
fi
done
echo "$i: '$max_word' ($max_len characters)"
fi
done
Default Behavior
report_home_space () {
local format="%8s%10s%10s\n"
local i dir_list total_files total_dirs total_size user_name
if [[ "$(id -u)" -eq 0 ]]; then
dir_list=/home/*
user_name="All Users"
else
dir_list="$HOME"
user_name="$USER"
fi
echo "<h2>Home Space Utilization ($user_name)</h2>"
for i in $dir_list; do
total_files="$(find "$i" -type f | wc -l)"
total_dirs="$(find "$i" -type d | wc -l)"
total_size="$(du -sh "$i" | cut -f 1)"
echo "<H3>$i</H3>"
echo "<pre>"
printf "$format" "Dirs" "Files" "Size"
printf "$format" "----" "-----" "----"
printf "$format" "$total_dirs" "$total_files" "$total_size"
echo "</pre>"
done
return
}
This improved version:
Superuser Privileges
The script checks for superuser privileges to determine whether to report on all
user home directories or just the current user's home directory.
Basic Parameters
Simple form: $a
Braced form: ${a}
a="foo"
echo "${a}_file" # Outputs: foo_file
Expansion Description
${parameter:-word} Use default value if parameter is unset/empty
${parameter:=word} Assign default value if parameter is unset/empty
${parameter:?word} Display error if parameter is unset/empty
Expansion Description
${parameter:+word} Use alternate value if parameter is set/non-empty
Examples:
foo=
echo ${foo:-"default value"} # Outputs: default value
echo ${foo:="new default"} # Assigns new value
echo ${foo:?"parameter empty"} # Displays error if empty
echo ${foo:+"alternate value"} # Uses alternate if set
Assignment Restriction
String Operations
Expansion Description
${#parameter} String length
${parameter:offset} Extract substring from offset
${parameter:offset:length} Extract substring of given length
${parameter#pattern} Remove shortest match from start
${parameter##pattern} Remove longest match from start
${parameter%pattern} Remove shortest match from end
${parameter%%pattern} Remove longest match from end
${parameter/pattern/string} Replace first match
Expansion Description
${parameter//pattern/string} Replace all matches
${parameter/#pattern/string} Replace match at beginning
${parameter/%pattern/string} Replace match at end
Examples:
file="document.txt.bak"
echo ${file#*.} # Outputs: txt.bak
echo ${file##*.} # Outputs: bak
Efficiency
Using parameter expansion for string manipulation can be more efficient than
external commands like sed or cut
Case Conversion
Expansion Description
${parameter,,pattern} Convert to lowercase
${parameter,pattern} Convert first char to lowercase
${parameter^^pattern} Convert to uppercase
${parameter^pattern} Convert first char to uppercase
Example:
str="aBcDeF"
echo ${str,,} # Outputs: abcdef
echo ${str,} # Outputs: aBcDeF
echo ${str^^} # Outputs: ABCDEF
echo ${str^} # Outputs: ABcDeF
Case Normalization
Number Bases
Notation Description
number Decimal (base 10)
0number Octal (base 8)
0xnumber Hexadecimal (base 16)
base#number Arbitrary base
Operators
Operator Description
+, - Addition, subtraction
*, / Multiplication, integer division
** Exponentiation
Operator Description
% Modulo (remainder)
Integer Division
Shell arithmetic only works with integers. Results of division are always whole
numbers.
Assignment Operators
Operator Equivalent
parameter = value Simple assignment
parameter += value parameter = parameter + value
parameter -= value parameter = parameter - value
parameter *= value parameter = parameter * value
parameter /= value parameter = parameter / value
parameter %= value parameter = parameter % value
parameter++ Post-increment
parameter-- Post-decrement
++parameter Pre-increment
--parameter Pre-decrement
Increment/Decrement Behavior
Bit Operations
Operator Description
~ Bitwise negation
<< Left bitwise shift
Operator Description
>> Right bitwise shift
& Bitwise AND
` `
^ Bitwise XOR
Logical Operators
Operator Description
<= , >= Less than or equal, greater than or equal
<, > Less than, greater than
== , != Equal to, not equal to
&& , `
expr1 ? expr2 : expr3 Ternary operator
Logical Evaluation
Basic usage:
bc < script.bc
bc <<< "2+2"
Interactive mode:
bc -q
principal=$1
interest=$2
months=$3
bc <<- EOF
scale = 10
i = $interest / 12
p = $principal
n = $months
a = p * ((i * ((1 + i) ^ n)) / (((1 + i) ^ n) - 1))
print a, "\n"
EOF
bc Features
bc supports variables, loops, and user-defined functions. Refer to the man page
for full documentation.
Here are extensive notes on the provided content using markdown language:
Array Limitations
Unlike many programming languages that support multidimensional arrays, bash
arrays are limited to a single dimension.
Creating an Array
Arrays can be created in two ways:
a[1]=foo
echo ${a[1]}
declare -a a
Braces Usage
When accessing array elements, use braces to prevent the shell from attempting
pathname expansion:
echo ${a[1]}
name[subscript]=value
Array Operations
Outputting Entire Array Contents
Use * or @ subscripts to access all elements:
Quoting Difference
When quoted, "${animals[*]}" results in a single word, while
"${animals[@]}" preserves individual elements.
${!array[*]}
${!array[@]}
foo=(a b c)
foo+=(d e f)
Sorting an Array
Example script for sorting:
#!/bin/bash
a=(f e d c b a)
a_sorted=($(for i in "${a[@]}"; do echo $i; done | sort))
echo "Sorted array: ${a_sorted[@]}"
Deleting an Array or Elements
Use the unset command:
When using unset with array elements, quote the element to prevent pathname
expansion:
unset 'foo[2]'
Associative Arrays
Supported in bash 4.0 and later
Use strings as indexes instead of integers
Must be created with declare -A
Example:
declare -A colors
colors["red"]="#ff0000"
colors["green"]="#00ff00"
colors["blue"]="#0000ff"
echo ${colors["blue"]}
Certainly! I'll create extensive and understandable notes using markdown language,
incorporating the requested notations for notes, tips, and warnings. I'll use ## for the
biggest titles, present all tables, and enclose inline commands in double square
brackets. Here are the notes:
36. exotica
Group Commands and Subshells
Group Commands
Syntax:
Subshells
Syntax:
Syntax Requirements
Key Differences:
1. Group commands execute in the current shell
2. Subshells execute in a child copy of the current shell
Uses:
Managing redirection for multiple commands
Combining results of several commands into a single stream for pipelines
Example:
Group commands are generally preferable to subshells as they are faster and
require less memory.
Process Substitution
Syntax for processes that produce standard output:
<(list)
>(list)
Example:
Useful Application
Process substitution is often used with loops containing read, especially when
processing directory listings.
Traps
Traps allow scripts to respond to signals, ensuring proper termination and cleanup.
Syntax:
Example:
It's common practice to specify a shell function as the command for a trap,
improving readability and maintainability.
exit_on_signal_SIGINT () {
echo "Script interrupted." 2>&1
exit 0
}
trap exit_on_signal_SIGINT SIGINT
Temporary Files
Security Concerns
When creating temporary files, especially for programs running with superuser
privileges, it's crucial to use nonpredictable filenames to avoid temp race
attacks.
Best Practices:
1. Use mktemp to create and name temporary files
2. For regular users, consider creating a temporary directory in the user's home
folder
tempfile=$(mktemp /tmp/foobar.$$.XXXXXXXXXX)
Asynchronous Execution
The wait command allows a parent script to pause until a specified child process
finishes.
Example:
Parent script:
async-child &
pid=$!
# ... other commands ...
wait "$pid"
Child script:
# Perform tasks
Named Pipes
Named pipes (FIFOs) allow communication between processes using file-like
interfaces.
mkfifo pipe1
Using Named Pipes:
Terminal 1:
ls -l > pipe1
Terminal 2:
Blocking Behavior
Writing to a named pipe blocks until another process reads from it, and vice
versa.
Further Reading
1. bash man page: "Compound Commands" and "EXPANSION" sections
2. Advanced Bash-Scripting Guide: Process substitution
3. Linux Journal articles on named pipes (September 1997 and March 2009)
These notes cover the main concepts from the provided text, including group
commands, subshells, process substitution, traps, temporary files, asynchronous
execution, and named pipes. The notes are structured using markdown, with
appropriate headings, code blocks, and special notations for notes, tips, and
warnings as requested.