diff --git a/chapters/ch04-system.tex b/chapters/ch04-system.tex index 78ceaa1..9dc8daf 100644 --- a/chapters/ch04-system.tex +++ b/chapters/ch04-system.tex @@ -220,4 +220,43 @@ command 1> file.txt command 2> file.txt \end{Verbatim} +\section{Command Substitution}\index[concepts]{command substitution} +\lettrine{O}{ccasionally} you may need to use the output of one command as the argument of another command. + +For example, suppose you have a folder full of pdfs that you want to combine into a single pdf using \texttt{pdftk}\index{pdftk}, and you want to join them in alphabetical order. You could do something like this: + +\begin{Verbatim}[frame=lines] +pdftk a.pdf b.pdf c.pdf d.pdf e.pdf f.pdf cat output merged.pdf +\end{Verbatim} + +However, if you have a lot of pdf files, that becomes very tedious. Using command substitution, we can use the \texttt{ls} command to sort that list of files and then use the output of that command as the input to \texttt{pdftk}: + +\begin{Verbatim}[frame=lines] +pdftk $(ls -v *.pdf) cat output merged.pdf +\end{Verbatim} +%$ + +In place of the dollar sign/parentheses construction, you can also use grave accents. Here is an example where we can use the \texttt{date} command as a variable in scripts: + +\begin{Verbatim}[frame=lines] +echo "Today is `date`" +\end{Verbatim} + +\noindent{}which returns + +\begin{Verbatim}[] +Today is Thu Sep 17 09:39:44 AM EDT 2026 +q\end{Verbatim} + +And of course, you can pass options to the substituted command as well: + +\begin{Verbatim}[frame=lines] +echo "Today is day #`date +%j` of the year" +\end{Verbatim} + +\noindent{}which returns + +\begin{Verbatim}[] +Today is day #260 of the year +\end{Verbatim} \ No newline at end of file