Linux › Section K · Shell scripts › Topic K.7
Subshells, including files, and reading input
Three features decide where a script's commands run and where its data comes from: subshells give a throwaway copy of the environment, sourcing pulls another file into the current shell, and read takes input from the user. Shell functions, which package commands under a name, complete the toolkit.
Subshells: a disposable environment
Commands in parentheses run in a subshell, a copy of the current shell with the same variables and working directory. Changes made inside vanish when it ends. In a directory k7 with a subdirectory logs, (cd logs; pwd) prints a path ending in k7/logs, but the next pwd prints one ending in k7 again. Variables behave the same way: after x=1, (x=2; echo "inside x=$x") prints inside x=2, yet echo "outside x=$x" prints outside x=1. Braces group commands without a subshell: { x=3; echo "braces x=$x"; } changes x for good, and they need spaces inside and a semicolon before }. Subshells suit temporary changes, such as working in another directory for one command.
One-off environment changes
Changing a variable for a single command is so common that the shell has a shortcut needing no subshell: write the assignment just before the command. greeting=hi bash -c 'echo "child sees: $greeting"' prints child sees: hi, while the parent's $greeting stays empty afterwards. The same form gives a program a modified PATH, as in PATH=/opt/tool/bin:$PATH tool, or another locale, as in LANG=C sort names.txt. The parenthesised version, (PATH=/opt/tool/bin:$PATH; tool), works too but costs an extra process. Both are safer than changing a variable and remembering to change it back.
Subshells you did not ask for
Some subshells appear without parentheses. In bash, each command in a pipeline runs in its own subshell. So count=0; printf 'a\nb\nc\n' | while read -r l; do count=$((count+1)); done; echo "count=$count" prints count=0: the loop counted three lines, but in a subshell that then vanished. Redirecting a file into the loop instead, done < three.txt, keeps the loop in the main shell and prints count=3. bash's process substitution, done < <(printf ...), also gives 3. Command substitution, $( ), always runs in a subshell, which is why a variable set inside it never reaches the script. When a value goes missing after a loop, suspect a pipe.
Worked example: copying a tree through a pipe
Copy the directory orig, with its subdirectory sub and file f.txt, into an existing directory target, keeping modes and timestamps. 1. Write the tree to standard output as an archive: tar cf - orig, where - means standard output. 2. Pipe it into a subshell that changes directory and unpacks standard input: | (cd target && tar xf -). 3. Using && means tar runs only if cd succeeded; with a ; a mistyped target would unpack into the current directory instead. 4. Run it and check: find target lists target/orig, target/orig/sub and target/orig/sub/f.txt. 5. The cd affected only the receiving tar. Warning: confirm that target exists and is not inside orig before running such a command.
Including other files with . and source
The dot command, . file, reads a file and runs its commands in the current shell, not a new one, so its variables and functions stay defined. This is called sourcing. With settings.conf holding backup_dir=/srv/backup and keep_days=14, a script containing . ./settings.conf prints Backing up to /srv/backup, keeping 14 days. Running the file as a program instead, sh settings.conf, starts a child shell; afterwards $backup_dir is still empty in the caller, and after sourcing it holds /srv/backup. bash also accepts source file, but . is the POSIX form, and dash knows only that. Give a path such as ./settings.conf: a name without a slash is looked up on the PATH first.
Reading input with read
read takes one line from standard input and stores it in variables. echo "Ada Lovelace" | { read -r first last; echo "first=$first last=$last"; } prints first=Ada last=Lovelace; the braces keep read and echo in the same subshell. As in "Loops and command substitution", -r keeps backslashes literal and the last variable takes the rest of the line. read returns 0 when it gets a line, even an empty one, and 1 at end of input, which is what ends a while read loop. bash adds -p "Name: " to show a prompt and -s to hide typing for passwords; in sh, print the prompt first with printf.
Worked example: an "Are you sure?" prompt
A script ask.sh must confirm before a dangerous step. 1. Prompt without a newline: printf 'Delete all files in %s? [y/N] ' "$1". 2. Read the reply: read -r answer. 3. Decide with case $answer in, where y|Y|yes) runs the action, here just echo "deleting (pretend)", and *) prints cancelled, then esac. The capital N in [y/N] signals that anything else means no. 4. Test with piped answers: echo y | sh ask.sh /srv/old printed the prompt and deleting (pretend), and echo no gave cancelled. 5. Test the edge case: with < /dev/null, read hits end of input at once, answer is empty and the script prints cancelled, the safe default for a script run with no one at the keyboard.
Shell functions
A function names a group of commands so a script can reuse them: square() { local n=$1; echo $((n * n)); }. Call it like a command, square 7, which printed 49. Inside, $1, $2, $# and "$@" are the function's own arguments, and the script's come back when it finishes. return n sets its exit status, so it can be used in if. By default variables are shared with the whole script: with n=1 and f() { n=5; }, calling f changes n to 5. local, provided by bash and dash though not by POSIX, confines a variable to the function: with n=1 and g() { local n=7; }, calling g leaves n at 1. Define functions before calling them, and put a shared set in a file that scripts source.
Worked example: a validating function
A script checks values before squaring them. 1. Define is_number() with a case on $1: the patterns ''|*[!0-9]*) return 1 reject an empty string or anything containing a non-digit, and *) return 0 accepts the rest. 2. Define square() as above and a log() function that writes the time and "$*" to standard error. 3. Set n=99, call log "starting", then loop over 7, x12 and an empty string, running if is_number "$v"; then echo "$v squared is $(square "$v")" with an else that reports the value. 4. The run printed 7 squared is 49, [x12] is not a number, [] is not a number, and finally n is still 99. 5. Check: local n inside square protected the script's n, and the log line went to standard error, not into the results.
Common mistakes to avoid
First, expecting cd or a variable set inside ( ) to last after it. Second, piping into while read and losing the variables set in the loop. Third, running a settings file instead of sourcing it with . ./file. Fourth, using source or read -p in a #!/bin/sh script on a system where sh is dash. Fifth, joining cd and the next command with ; instead of &&, so a failed cd sends the work to the wrong directory. Sixth, forgetting local, so a function silently overwrites the script's variables.
Key takeaways
( commands ) run in a subshell whose changes disappear; { commands; } group without one. VAR=value cmd changes the environment for one command only. Pipeline stages and $( ) run in subshells, so redirect a file into a while read loop instead of piping. . file sources a file into the current shell, keeping its variables. read -r var reads a line, returns 1 at end of input and, with case, makes a safe confirmation prompt. name() { ...; } defines a function with its own $1 and return status; local keeps its variables private.
Flashcards
Flashcard
Run cmds in a subshell; changes vanish afterwards
Test your understanding
Question 1 of 5
After x=1, a script runs (x=2; cd /tmp) and then echo $x. What does it print, and where is the script now?
Question 2 of 5
In bash, a script sets count=0, pipes a two-line file with cat into while read -r l; do count=$((count+1)); done, then runs echo $count. Why does it print 0?
Question 3 of 5
settings.conf contains backup_dir=/srv/backup. Which line makes $backup_dir available to the rest of a script?
Question 4 of 5
A confirmation script reads a reply and treats anything except y, Y or yes as cancel. What does it do when run with input from /dev/null?
Question 5 of 5
A script sets n=1 and defines f() { n=5; }. After it calls f, what is n, and what would keep it at 1?
