Shells and Shell Scripting
What the exam tests
The Shells and Shell Scripting domain tests how Bash constructs its environment and how you write scripts that behave predictably under cron, sudo, and pipelines. LPIC-1 102-500 expects you to know startup-file order, quoting, tests, loops, exit statuses, and basic SQL access.
Core rules
- A login shell reads
/etc/profile, then the first existing file among~/.bash_profile,~/.bash_login, and~/.profile. An interactive non-login shell reads~/.bashrc;/etc/bash.bashrcand/etc/profile.d/*.share common system hooks.source fileor. fileruns it in the current shell. - Single quotes protect everything; double quotes still expand
$, backticks, and$(...)."$@"preserves each positional parameter as a separate word;"$*"joins them. [ ... ]is the POSIX test command;[[ ... ]]is Bash syntax with pattern matching. File tests include-f,-d,-r,-w,-x; string tests-z,-n,=; numeric tests-eq,-ne,-lt.- A script starts with a shebang such as
#!/bin/bash, needs execute permission, and receives$0,$1,$#, and$?. Exit 0 means success. - SQL basics may appear through
sqlite3or a client:SELECT ... FROM ... WHERE ... ORDER BY ...,INSERT,UPDATE,DELETE, andCREATE TABLE.
Worked example
#!/bin/bash
set -u
if [ "$(id -u)" -ne 0 ]; then
echo 'run as root' >&2
exit 1
fi
for f in /etc/hosts /etc/fstab; do
[ -f "$f" ] || continue
cp -a "$f" "/root/$(basename "$f").bak"
done
$(id -u) returns the effective UID, so the guard rejects non-root users. >&2 writes the error to stderr; exit 1 sets a failure status. Quoting "$f" preserves spaces, and [ -f ] skips missing files. set -u turns an unset variable into an error, which catches typos in unattended jobs.
Traps
Do not assume ~/.bashrc runs in a script or cron job; non-interactive shells do not read it by default. $? is overwritten by every command, including echo, so capture it immediately. Unquoted variables break on spaces and empty values. = is string comparison inside [ ]; use -eq for numbers. Aliases are not expanded in non-interactive scripts unless shopt -s expand_aliases is set, so use functions instead.