Dit deel is nog niet vertaald. Je ziet de Engelse tekst.
$ als gewone gebruiker# als root (of met sudo)
Vaardigheden in dit hoofdstuk
- Subshells, process substitution, traps en veilige tijdelijke bestanden gebruiken
Use group commands and subshells
{ commands; } is a group command (runs in the current shell). (commands) is a subshell (runs in a copy of the shell). Both let you redirect the output of many commands at once.
ls -l > output.txt
echo "Listing of foo.txt" >> output.txt
cat foo.txt >> output.txt
{ ls -l; echo "Listing of foo.txt"; cat foo.txt; } > output.txt
(ls -l; echo "Listing of foo.txt"; cat foo.txt) > output.txt- In
{ }you need spaces after{and a;(or new line) before}. - A subshell is slower, and its changes (variables,
cd) are lost when it ends. A group command keeps them. - Pipelines also run in subshells: that is why
echo foo | read xdoes not work.
Use process substitution
<(command) gives the output of a command as if it were a file. >(command) gives the input of a command as a file.
read < <(echo "foo")
echo $REPLY
foo
echo <(echo "foo")
/dev/fd/63
diff <(ls dir1) <(ls dir2)
while read -r attr links owner group size date time filename; do echo "$filename: $size"; done < <(ls -l --time-style="+%F %H:%M" | tail -n +2)- The loop with
< <(…)runs in the current shell, so its variables stay after the loop (unlike a pipe). diff <(cmd1) <(cmd2)compares the output of two commands without temporary files.
Op het werk
diff <(ssh web1 cat /etc/nginx/nginx.conf) <(ssh web2 cat /etc/nginx/nginx.conf) compares a file on two servers.
Build commands with eval
eval takes its arguments, joins them into a string, and runs that string as a command. The line is expanded two times.
cmd='ls -l'
$cmd
var='$HOME'
echo $var
$HOME
eval echo $var
/home/me
for n in 1 2 3; do eval "item$n=value$n"; done
echo $item2
value2evalis useful when a command (for example a long pipeline) must be built from pieces at run time.- The book's example is a Wordle helper: from a pattern like
..o.tplus "contains a and b, not l", it builds a pipeline ofgrepcommands of the right length and runs it withevalon/usr/share/dict/words.
pipeline="grep -E '^${pattern}$' /usr/share/dict/words"
for arg in "$@"; do
case "$arg" in
+*) pipeline+=" | grep -i '${arg#+}'" ;;
-*) pipeline+=" | grep -iv '${arg#-}'" ;;
esac
done
eval "$pipeline"Let op
Be careful with eval. If any part comes from user input, the user can run any command (; rm -rf ~). Check the input strictly, or use arrays and functions instead.
Catch signals with trap
trap 'commands' signals runs commands when the script gets a signal: clean up, or ignore Ctrl-c.
#!/bin/bash
# trap-demo: simple signal handling demo
trap "echo 'I am ignoring you.'" SIGINT SIGTERM
for i in {1..5}; do
echo "Iteration $i of 5"
sleep 5
done#!/bin/bash
exit_on_signal_SIGINT () {
echo "Script interrupted." 2>&1
exit 0
}
exit_on_signal_SIGTERM () {
echo "Script terminated." 2>&1
exit 0
}
trap exit_on_signal_SIGINT SIGINT
trap exit_on_signal_SIGTERM SIGTERM
for i in {1..5}; do
echo "Iteration $i of 5"
sleep 5
doneSIGKILLandSIGSTOPcannot be caught.trap cleanup EXITrunscleanupwhenever the script ends, for any reason: the best place to remove temporary files.
Make temporary files safely
Use mktemp for temporary files. A guessable name in /tmp (like /tmp/myscript.$$) can be attacked by other users.
mktemp
/tmp/tmp.L3pJqQa0Hx
mktemp /tmp/report.XXXXXX
/tmp/report.Zp4ZQq
mktemp -dtempfile="$(mktemp /tmp/"${0##*/}".XXXXXX)" || exit 1
trap 'rm -f "$tempfile"' EXIT
sort data.txt > "$tempfile"
head "$tempfile"- Each
Xbecomes a random character.-dmakes a temporary directory. - For files of your own scripts, a directory like
~/tmpis also safer than the shared/tmp.
Run jobs at the same time with wait
Start commands in the background with & and wait for them with wait. $! holds the PID of the last background job.
#!/bin/bash
# async-parent: asynchronous execution demo (parent)
echo "Parent: starting..."
echo "Parent: launching child script..."
async-child &
pid=$!
echo "Parent: child (PID= $pid) launched."
echo "Parent: continuing..."
sleep 2
echo "Parent: pausing to wait for child to finish..."
wait "$pid"
echo "Parent: child is finished. Continuing..."
echo "Parent: parent is done. Exiting."for h in web1 web2 web3 db1; do
ssh "$h" uptime > "up-$h.txt" &
done
wait
cat up-*.txtwaitwithout an argument waits for all background jobs.
Use named pipes
A named pipe (FIFO) is a pipe with a name in the filesystem. One process writes into it, another reads from it, like a normal | between two separate shells.
Summary of the book
You went from the first prompt to scripts with functions, loops, options, arrays, traps and parallel jobs. Keep practising: automate one real task each week.
| Part | What you can do now |
|---|---|
| 1. Learning the shell | Move around, manage files, redirect, use pipes, permissions and processes |
| 2. Configuration | Set up the environment, edit with vi, design the prompt |
| 3. Tools | Packages, disks, network, find, backups, regex, text processing, printing, compiling |
| 4. Scripts | Variables, functions, if/case, loops, input, options, strings, numbers, arrays, traps |
1What is the difference between { cmd; } and (cmd)?
{ } runs in the current shell (changes stay); ( ) runs in a subshell (changes are lost).
2How do you make sure a temporary file is removed when the script ends?
Make it with mktemp and add trap 'rm -f "$tempfile"' EXIT.
3Why is eval dangerous with user input?
The input is run as a command, so a user could inject any command.