-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
16-if-statements.sh
119 lines (96 loc) · 2.79 KB
/
16-if-statements.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#!/bin/bash
echo "
#########################
## Example 16.1: #
## a basic if statement #
#########################
"
# `if` can run any command. For example, touch!
if touch files/test.txt
then
echo 'did a thing!'
fi
# this one will fail because /asdf doesn't exist
if touch /asdf/asdf.txt
then
echo 'it succeeded'
else
echo 'it failed'
fi
echo "
##########################
## Example 16.2: #
## a 1-line if statement #
##########################
"
# if COMMAND; then THING; fi
# the semicolons need to go in exactly those places, otherwise
# it won't work (try putting the semicolons somewhere else!)
if touch files/test.txt; then echo 'success'; fi
echo "
########################################
## Example 16.3: #
## run [ by itself to see how it works #
########################################
"
# first, let's run the program [ by itself
/usr/bin/[ -e files/lines.txt ]
echo $? # $? is the exit code of the most recent program run
echo 'the exit code was 0, so it succeeded'
/usr/bin/[ -e files/doesntexist.txt ]
echo $? # $? is the exit code of the most recent program run
echo 'the exit code was 1, because doesntexist.txt doesn't exist
echo "
#######################################
## Example 16.3: #
## testing if a file exists with if [ #
#######################################
"
if [ -e files/lines.txt ]
then
echo "files/lines.txt exists!"
fi
# [ is actually a bash builtin, but it acts like the program
# /usr/bin/[ that we just used above
echo "
########################################
## Example 16.4: #
## testing if a file exists with if [[ #
########################################
"
# most things that work with if [ will also work with if [[
if [[ -e files/lines.txt ]]
then
echo "files/lines.txt exists!"
fi
echo "
###########################
## Example 16.5: #
## negating a test with ! #
###########################
"
# ! will check if a command fails
if ! [ -e files/doesntexist.txt ]
then
echo "files/doesntexist.txt doesn't exist!"
fi
echo "
####################################################
## Example 16.6: #
## using && to check if 2 conditions are both true #
####################################################
"
if [ -e file1 ] && [ -e file2 ]
then
echo file1 and file2 both exist
else
echo "they don't"
fi
echo "
#################################################
## Example 16.7: #
## try running #
## $ man test #
## to see what else you can put in 'if [ ... ]' #
#################################################
"