# [ test ] || action # Perform simple single command if test is false dirname="/tmp/testdir" [ -d "$dirname" ] || mkdir "$dirname"
Instead of pipes, you can use two ampersands to test if something is true. In the following example, a command is being tested to see if it includes at least three command-line arguments:
# [ test ] && {action} # Perform simple single action if test is true [ $# -ge 3 ] && echo "There are at least 3 command line arguments."
You can combine the &&
and ||
operators to make a quick, one-line if…then…else
. The following example tests that the directory represented by $dirname
already exists. If it does, a message says the directory already exists. If it doesn't, the statement creates the directory:
# dirname=mydirectory [ -e $dirname ] && echo $dirname already exists || mkdir $dirname
Another frequently used construct is the case
command. Similar to a switch
statement in programming languages, this can take the place of several nested if
statements. The following is the general form of the case
statement:
case "VAR" in Result1) { body };; Result2) { body };; *) { body } ;; esac
Among other things, you can use the case
command to help with your backups. The following case
statement tests for the first three letters of the current day ( case 'date +%a' in
). Then, depending on the day, a particular backup directory ( BACKUP
) and tape drive ( TAPE
) are set.
# Our VAR doesn't have to be a variable, # it can be the output of a command as well # Perform action based on day of week case `date +%a` in "Mon") BACKUP=/home/myproject/data0 TAPE=/dev/rft0 # Note the use of the double semi-colon to end each option ;; # Note the use of the "|" to mean "or" "Tue" | "Thu") BACKUP=/home/myproject/data1 TAPE=/dev/rft1 ;; "Wed" | "Fri") BACKUP=/home/myproject/data2 TAPE=/dev/rft2 ;; # Don't do backups on the weekend. *) BACKUP="none" TAPE=/dev/null ;; esac
The asterisk ( *
) is used as a catchall, similar to the default
keyword in the C programming language. In this example, if none of the other entries are matched on the way down the loop, the asterisk is matched and the value of BACKUP
becomes none
. Note the use of esac
, or case
spelled backwards, to end the case
statement.
Loops are used to perform actions over and over again until a condition is met or until all data has been processed. One of the most commonly used loops is the for…do
loop. It iterates through a list of values, executing the body of the loop for each element in the list. The syntax and a few examples are presented here:
for VAR in LIST do { body } done
The for
loop assigns the values in LIST to VAR one at a time. Then, for each value, the body in braces between do
and done
is executed. VAR
can be any variable name, and LIST
can be composed of pretty much any list of values or anything that generates a list.
for NUMBER in 0 1 2 3 4 5 6 7 8 9 do echo The number is $NUMBER done for FILE in `/bin/ls` do echo $FILE done
You can also write it this way, which is somewhat cleaner:
for NAME in John Paul Ringo George ; do echo $NAME is my favorite Beatle done
Each element in the LIST
is separated from the next by white space. This can cause trouble if you're not careful because some commands, such as ls -l
, output multiple fields per line, each separated by white space. The string done
ends the for
statement.
If you're a die-hard C programmer, bash allows you to use C syntax to control your loops:
LIMIT=10 # Double parentheses, and no $ on LIMIT even though it's a variable! for ((a=1; a <= LIMIT ; a++)) ; do echo "$a" done
The ″while…do″ and ″until…do″ loops
Two other possible looping constructs are the while…do
loop and the until…do
loop. The structure of each is presented here:
while condition until condition do do { body } { body } done done
The while
statement executes while the condition is true. The until
statement executes until the condition is true—in other words, while the condition is false.
Here is an example of a while
loop that outputs the number 0123456789:
N=0 while [ $N -lt 10 ] ; do echo -n $N let N=$N+1 done
Another way to output the number 0123456789 is to use an until
loop as follows:
N=0 until [ $N -eq 10 ] ; do echo -n $N let N=$N+1 done
Trying some useful text manipulation programs
Bash is great and has lots of built-in commands, but it usually needs some help to do anything really useful. Some of the most common useful programs you'll see used are grep
, cut
, tr
, awk
, and sed
. As with all of the best UNIX tools, most of these programs are designed to work with standard input and standard output, so you can easily use them with pipes and shell scripts.
The general regular expression parser
The name general regular expression print ( grep
) sounds intimidating, but grep
is just a way to find patterns in files or text. Think of it as a useful search tool. Gaining expertise with regular expressions is quite a challenge, but after you master it, you can accomplish many useful things with just the simplest forms.
For example, you can display a list of all regular user accounts by using grep
to search for all lines that contain the text /home
in the /etc/passwd
file as follows:
$ grep /home /etc/passwd
Or you could find all environment variables that begin with HO
using the following command:
$ env | grep ^HO
The ^
in the preceding code is the actual caret character, ^
, not what you'll commonly see for a backspace, ^H
. Type ^, H, and O(the uppercase letter) to see what items start with the uppercase characters HO.
To find a list of options to use with the grep
command, type man grep.
Remove sections of lines of text (cut)
The cut
command can extract fields from a line of text or from files. It is very useful for parsing system configuration files into easy-to-digest chunks. You can specify the field separator you want to use and the fields you want, or you can break up a line based on bytes.
The following example lists all home directories of users on your system. This grep
command line pipes a list of regular users from the /etc/passwd
file and displays the sixth field ( -f6
) as delimited by a colon ( -d':'
). The hyphen at the end tells cut
to read from standard input (from the pipe).
$ grep /home /etc/passwd | cut -d':' -f6 - /home/chris /home/joe
Translate or delete characters (tr)
The tr
command is a character-based translator that can be used to replace one character or set of characters with another or to remove a character from a line of text.
The following example translates all uppercase letters to lowercase letters and displays the words mixed upper and lower case
as a result:
$ FOO="Mixed UPpEr aNd LoWeR cAsE" $ echo $FOO | tr [A-Z] [a-z] mixed upper and lower case
Читать дальше