Geavanceerd
Zoeken inSamenvattingen
Zo zoek je
  • Woorden vinden lestitels, tekst en code. Filter op soort (gidsen, cursussen, programma's, boeken) of blijf in dit boek.
  • book:rhcsa en ch:8 maken de zoektocht kleiner; #code vindt een woord alleen in commando's van de lessen.
  • "twee woorden" vindt precies die zin.
  • Gewone woorden vinden namen, teksten en voorbeelden.
  • ↑ ↓ bewegen · Enter openen · Esc sluiten · / zoeken
Probeer:

Hoofdstuk 36Naam in het boek: Exotica

Exotica: advanced tricks

The last chapter shows features you do not need every day, but that solve hard problems in a clean way: group commands and subshells, process substitution, building commands with eval, traps for signals, safe temporary files, running jobs at the same time with wait, and named pipes.

  • 8 Lessen
  • 9 Commando's
  • 1 Labs

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

36.1

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.

without and with a group
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
{ ls -l; echo "Listing of foo.txt"; cat foo.txt; } | lpr
(cd /tmp && ls)
pwd
/home/me
  • 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 x does not work.

36.2

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.

36.3

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
value2
  • eval is 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.t plus "contains a and b, not l", it builds a pipeline of grep commands of the right length and runs it with eval on /usr/share/dict/words.
the idea of the Wordle helper (short version)
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.

36.4

Catch signals with trap

trap 'commands' signals runs commands when the script gets a signal: clean up, or ignore Ctrl-c.

trap-demo
#!/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
trap-demo2: a function as handler
#!/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
done
  • SIGKILL and SIGSTOP cannot be caught.
  • trap cleanup EXIT runs cleanup whenever the script ends, for any reason: the best place to remove temporary files.

36.5

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 -d
safe temp file with clean-up
tempfile="$(mktemp /tmp/"${0##*/}".XXXXXX)" || exit 1
trap 'rm -f "$tempfile"' EXIT
 
sort data.txt > "$tempfile"
head "$tempfile"
  • Each X becomes a random character. -d makes a temporary directory.
  • For files of your own scripts, a directory like ~/tmp is also safer than the shared /tmp.

36.6

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.

async-parent
#!/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."
check many servers at the same time
for h in web1 web2 web3 db1; do
    ssh "$h" uptime > "up-$h.txt" &
done
wait
cat up-*.txt
  • wait without an argument waits for all background jobs.

36.7

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.

mkfifo pipe1
ls -l pipe1
prw-r--r--. 1 me me 0 Nov  8 pipe1
ls -l > pipe1
cat < pipe1
rm pipe1
  • The type letter in ls -l is p.
  • The writer waits ("blocks") until a reader opens the pipe. Run the two commands in two terminal windows.

36.8

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.

PartWhat you can do now
1. Learning the shellMove around, manage files, redirect, use pipes, permissions and processes
2. ConfigurationSet up the environment, edit with vi, design the prompt
3. ToolsPackages, disks, network, find, backups, regex, text processing, printing, compiling
4. ScriptsVariables, 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.

Oefenen

Alle commando's in dit hoofdstuk