Unit 4: Command Productivity, Scheduling, Performance, and ACLs
I. Orientation: Linux Administration as Controlled Automation
Linux system administration combines efficient command use, repeatable automation, timed execution, resource management, and precise access control. The governing principle is to make system behavior predictable: commands should be reproducible, jobs should run under known conditions, performance changes should be measurable, and file access should follow least privilege.
- Command interpretation: The shell reads a command line, expands variables and patterns, performs redirection, and starts a program.
- Automation: A Bash script stores commands in an executable sequence, while loops repeat operations over files, users, or command output.
- Scheduling:
atruns a user job once in the future;cronruns recurring jobs according to a time specification. - Performance control: Tuning changes should be selected from measurable symptoms such as CPU saturation, memory pressure, or excessive I/O wait.
- Permissions: Traditional permissions divide access among owner, group, and others; ACLs add named users and groups.
- Least privilege: Users and processes receive only the access and resources required for their tasks.
- Administrative context: Commands such as
systemctl,tuned-adm,setfacl, andgetfaclcommonly require appropriate privileges.
II. Command-Line Productivity and Shell Automation
The command line is most productive when commands are composable, output is redirected deliberately, and repeated work is expressed as a script or loop.
A. Improving Command-line Productivity
This topic concerns reducing repetitive typing while preserving clear, inspectable command behavior.
- History: Use
historyto inspect previous commands and!numberto rerun a history entry;Ctrl+rsearches interactively through command history. - Completion: Press
Tabto complete commands, paths, usernames, and options. Completion reduces spelling errors and exposes available files. - Aliases: Define short command names, such as:
BASHalias ll='ls -l'
An alias affects interactive shell use and is not automatically available to scripts. - Pipelines: The pipe sends standard output to another command:
BASHps aux | grep sshd
Here,ps auxproduces process data andgrepfilters matching lines. - Redirection:
>replaces a file,>>appends, and2>redirects standard error:
BASHcommand >output.txt 2>errors.txt - Command substitution:
$(command)inserts command output into another command, as inecho "Kernel: $(uname -r)". - Safe inspection: Use
man command,command --help, andtype commandto distinguish a binary, alias, function, or shell builtin.
B. Writing Simple Bash Scripts
A Bash script is a text file interpreted by Bash and used to make a sequence of administrative actions repeatable.
- Interpreter declaration: Begin with:
BASH#!/usr/bin/env bash
This selects Bash through the environment path. - Variables: Assign without spaces and expand with
$:
BASHuser_name="sam" echo "Account: $user_name" - Arguments:
$1is the first argument,$#is the argument count, and"$@"represents all arguments separately. - Conditions: Use
ifwith a test such as[[ -f "$file" ]], where-fchecks for a regular file. - Exit status: A successful command normally returns
0; failure returns a nonzero status.exit 1explicitly signals failure. - Execution safety: Quote variables such as
"$file"to preserve spaces and special characters. Make a script executable withchmod +x script.sh. - Defensive settings:
set -euo pipefailmakes many errors visible by stopping on failures, rejecting unset variables, and detecting pipeline failures; it should be used with awareness of commands that intentionally return nonzero statuses.
C. Running Commands More Efficiently Using Loops
Loops apply one operation to multiple values and eliminate manual repetition.
- File iteration: A
forloop can process matching files:
BASHfor file in /var/log/*.log; do printf '%s\n' "$file" done
The variablefilereceives each pathname produced by the glob. - While loops: A
whileloop is suitable for reading input line by line:
BASHwhile IFS= read -r line; do printf '%s\n' "$line" done < hosts.txt - Controlled repetition:
breakexits a loop, whilecontinueskips to its next iteration. - Robust filenames: For arbitrary filenames, prefer null-delimited pipelines such as
find ... -print0withread -d ''; ordinary whitespace splitting can corrupt names containing spaces. - Efficiency: One loop can perform a consistent operation across hundreds of files, but commands should be quoted and tested on a small sample before broad execution.
D. Matching Text in Command Output with Regular Expressions
Regular expressions describe text patterns, allowing administrators to select, validate, or transform command output.
- Basic matching:
grep 'error' app.logselects lines containingerror;grep -iignores case. - Anchors:
^rootmatches lines beginning withroot, whilebash$matches lines ending withbash. - Character and repetition patterns:
[0-9]matches one digit,.matches one character, and*repeats the preceding expression zero or more times. - Extended expressions:
grep -E 'sshd|httpd' services.txtmatches either service name.+means one or more occurrences in extended regular expressions. - Structured output:
awkis useful when fields matter, for exampleawk '$3 > 80 {print $1}', which prints field 1 when field 3 exceeds 80. - Limitations: Regular expressions match text, not semantic meaning; anchoring and field boundaries are necessary to avoid accidental matches.
III. Scheduling and Temporary Work
Linux scheduling separates one-time jobs from recurring jobs and provides controlled mechanisms for short-lived files.
A. Scheduling Future Tasks
Scheduling future tasks requires a command, execution time, environment, and account context.
- One-time versus recurring: Use
atfor one execution andcronfor repeated execution. A job scheduled withatdoes not repeat automatically. - Time expressions:
at 23:00schedules a job for a specified time;at now + 10 minutesexpresses a relative delay. - Environment: Scheduled jobs may have a smaller
PATH, no interactive terminal, and a different working directory. Use absolute command paths where practical. - Verification:
atqlists pendingatjobs, whileatrm JOB_IDremoves a queued job. - Permissions:
/etc/at.allowand/etc/at.denycan restrict which users may submitatjobs.
B. Scheduling a Deferred User Job
A deferred user job is a single command or script submitted to at and executed later by the scheduling service.
- Submission: Pipe a command into
at:
BASHecho "/home/sam/bin/backup.sh" | at 02:00
The command is submitted immediately but runs at 02:00. - Interactive submission: Running
at 02:00opens an input prompt; enter commands and finish withCtrl+d. - Output handling: Redirect output explicitly, for example:
BASHecho "/usr/bin/df -h > /home/sam/disk-report.txt" | at now + 1 hour - Job identity: The returned job number identifies the task for
atqandatrm. - Operational limitation: The job runs with the submitting user’s privileges, so it cannot modify protected system files without suitable authorization.
C. Scheduling Recurring System Jobs
Recurring jobs are defined in crontabs using five time fields followed by a command.
- Field order: The fields are minute, hour, day of month, month, and day of week:
TEXT0 2 * * * /usr/local/sbin/backup.sh
This runs daily at 02:00. - Special values:
*means every permitted value;*/15means every 15 units, such as every 15 minutes. - User crontab:
crontab -eedits the current user’s jobs;crontab -llists them. - System cron:
/etc/crontaband files under/etc/cron.d/include an additional username field:
TEXT0 2 * * * root /usr/local/sbin/backup.sh - Reliability: Use absolute paths, redirect output, and avoid assumptions about interactive shell variables. The
cronorcrondservice must be running.
D. Managing Temporary Files
Temporary files should be created safely, cleaned predictably, and protected from name collisions or unauthorized reading.
- Secure creation:
mktempcreates a unique temporary file or directory:
BASHtmpdir=$(mktemp -d) trap 'rm -rf "$tmpdir"' EXIT - Cleanup:
trapruns cleanup when the script exits;EXITcovers normal completion and many error paths. - Temporary directories:
/tmpis generally writable by users and commonly uses the sticky bit, so users cannot remove other users’ files there. - System cleanup:
systemd-tmpfilesapplies policies from configuration files, including cleanup ages and permissions. - Security risk: Never construct predictable names such as
/tmp/report.txt; an attacker may create a symbolic link before the administrator writes to it.
IV. Performance and Process Control
Performance administration measures resource behavior, applies an appropriate profile, and controls process priority according to operational need.
A. Tuning System Performance
System tuning changes kernel and service behavior to improve throughput, latency, power use, or responsiveness.
- CPU measurement:
topanduptimeshow load and process activity; a high load average indicates runnable or uninterruptible tasks, not CPU percentage alone. - Memory measurement:
free -hreports memory in human-readable units. Swap use and sustained reclaim can indicate memory pressure. - I/O measurement:
iostatidentifies device utilization and wait behavior; high%utilor latency can point to storage saturation. - Network measurement:
ss -tulpndisplays listening sockets and owning processes, whilesar -n DEVcan show interface activity. - Change discipline: Measure a baseline, change one relevant setting, and measure again. A performance improvement must be evaluated against latency, reliability, and resource cost.
B. Adjusting Tuning Profiles
Tuning profiles provide coordinated settings for common workloads instead of requiring every parameter to be changed separately.
- Profile manager: On systems using
tuned,tuned-adm activedisplays the current profile andtuned-adm listlists available profiles. - Selection: Apply a profile with:
BASHsudo tuned-adm profile throughput-performance
The profile name should match the workload and hardware. - Common goals:
throughput-performancefavors bulk processing;latency-performancereduces latency at possible power cost;powersaveprioritizes energy reduction. - Verification: Use
tuned-adm verifyto check whether the running system matches the selected profile. - Tradeoff: A profile is a coordinated policy, not a universal optimization; throughput, latency, energy use, and thermal behavior can conflict.
C. Influencing Process Scheduling
Process scheduling controls relative CPU preference and, for eligible tasks, scheduling class.
- Nice value: Normal processes commonly use a nice value from
-20to19; larger values mean lower CPU priority. Display values withps -eo pid,ni,comm. - Starting priority:
nice -n 10 commandlaunches a command with a lower priority than default. - Changing priority:
renice 10 -p PIDchanges an existing process. Increasing priority toward negative nice values normally requires root privileges. - Scheduling classes:
chrtcan inspect or set real-time policies such asSCHED_FIFO; real-time use can starve ordinary processes and requires strict control. - Correct interpretation: Nice values influence CPU competition; they do not reserve CPU time and do not improve I/O, memory, or application algorithm performance.
V. Access Control Lists
ACLs extend the traditional owner-group-other permission model when a file needs access rules for specific users or groups.
A. Controlling Access to Files with ACLs
This mechanism grants or removes permissions for named users and groups while retaining the traditional mode bits.
- Granting a user:
setfacl -m u:alex:rw file.txtgrants useralexread and write access. - Granting a group:
setfacl -m g:auditors:rX report/grants the group read access and directory traversal where applicable. - Removing an entry:
setfacl -x u:alex file.txtremoves the named-user ACL entry. - Recursive changes:
setfacl -R -m g:project:rX project/applies rules recursively; review the result because files and directories may require different permissions. - ACL support: The filesystem must support POSIX ACLs, and mount or filesystem configuration can affect availability.
B. Interpreting File ACLs
ACL interpretation requires reading both named entries and the effective permission mask.
- Display:
getfacl file.txtmay show:
TEXTuser::rw- user:alex:r-- group::r-- mask::r-- other::--- - Owner and other:
user::rw-is the owning user’s permission;other::---applies to everyone not matched by owner, named entries, or group rules. - Named entries:
user:alex:r--grantsalexread access independently of the owning user. - Mask:
mask::r--limits effective permissions for named users, named groups, and the owning group. A nominalrw-entry is effectivelyr--when the mask is read-only. - Mode display:
ls -lshows a+after permissions when extended ACL entries exist, such as-rw-r-----+.
C. Securing Files with ACLs
ACL security depends on precise entries, restrictive defaults, and regular review.
- Least privilege: Grant only required permissions, for example
setfacl -m u:auditor:r-- confidential.log; avoid broadrwxgrants. - Directory traversal: A user needs execute (
x) permission on each directory in a path to reach a file, even when the file itself is readable. - Default ACLs:
setfacl -m d:g:developers:rX shared/establishes inherited permissions for newly created content undershared/. - Removing excess access:
setfacl -b file.txtremoves all extended ACL entries, returning the file to basic permissions; use only when that reset is intended. - Auditing: Use
getfacl -R, inspect sensitive directories, and compare ACLs with the intended access policy. - Limitations: ACLs do not bypass mandatory access controls such as SELinux, file ownership restrictions, encryption, or application-level authorization.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →