Entering multiple-line commands interactively

In addition to its interactive capabilities, the shell also has a complete programming language of its own. Many programming features can be very handy at the interactive command line as well. Looping constructs, including for, until, and while, are often used this way. (Shell syntax is covered in more detail in Chapter 13.) When you begin a command such as these, which normally spans multiple lines, bash prompts you for the subsequent lines until a valid command has been completed. The prompt you receive in this case is stored in shell variable PS2, which by default is >. For example, if you wanted to repetitively execute a series of commands each time with a different argument from a known series, you could enter the following:

$ var1=1
$ var2=2
$ var3=3
$ echo $var1
1
$ echo $var2
2
$ echo $var2
3

Rather than entering each command manually, you can interactively use bash’s for loop construct to do the work for you. Note that indented style, such as what you might use in traditional programming, isn’t necessary when working interactively with the shell:

$ for var in $var1 $var2 $var3
> do
> echo $var
> done
1
2
3

You can also write this command on one line:

$ for var in $var1 $var2 $var3; do echo $var; done
1
2
3

The semicolons are necessary to separate the variables from the built-in bash functions.

Get LPI Linux Certification in a Nutshell, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.