Bash programming/Subshells

From Wikiversity
Jump to navigation Jump to search

Subshells are one way for a programmer to capture (usually with the intent of processing) the output from a program or script. Commands to be run inside a subshell are enclosed inside single parentheses and preceeded by a dollar sign:

DIRCONTENTS=$(ls -l)
echo ${DIRCONTENTS}

which is an unnecessary complication of simply typing "ls -l". However, this complication would be necessary if the programmer wanted to evaluate the output, or otherwise modify it, rather than simply presenting it to the user.


What is going on here is the script first takes the command or commands inside the subshell, in this case "ls -l" and runs it in it's own instance of the shell. The output (stdout) is not sent to the user, but rather, in this case, stored in the variable DIRCONTENTS.


Later, the programmer chooses to echo DIRCONTENTS but he could have checked it for the presence of a certain substring, ran a search and replace on it then displayed it, or extracted important information and discarded the rest.


In another example, a common way to loop through each file in a directory is to use the following for loop:

for FILE in $(find /home/james/documents -name \*.sh) ; do
    # Some sort of operation would go here, say:
    cat ${FILE}
done

To understand what is going on here, one first needs to understand the output of the subshell. This find command returns a newline separated list of file location that match the criteria (in this case, files that are in that directory or it's subdirectories that end with ".sh"). Next, this return is used in the for loop such that for every matching file, the variable FILE is set to it's path, which is used in the body of the for loop. In this case, the path is passed as an argument to cat, which displays the contents of the file.cation that match the criteria (in this case, files that are in that directory or it's subdirectories that end with ".sh"). Next, this return is used in the for loop such that for every matching file, the variable FILE is set to it's path, which is used in the body of the for loop. In this case, the path is passed as an argument to cat, which displays the contents of the file.