Newer
Older
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
<code>STRING = STRING</code>: True if the string matches the glob
pattern (if you quote the glob pattern, the strings have to match
exactly). * <code>STRING != STRING</code>: True if the string does not
match the glob pattern (if you quote the glob pattern, the strings
just have to be different). * <code>STRING < STRING</code>: True if
the first string sorts before the second. *{" "}
<code>STRING > STRING</code>: True if the first string sorts after
the second.
</li>
<li>
<code>EXPR -a EXPR</code>: True if both expressions are true (logical
AND).
</li>
<li>
<code>EXPR -o EXPR</code>: True if either expression is true (logical
OR).
</li>
<li>
<code>! EXPR</code>: Inverts the result of the expression (logical
NOT).
</li>
<li>
<code>EXPR && EXPR</code>: Much like the ‘-a’ operator of
test, but does not evaluate the second expression if the first already
turns out to be false.
</li>
<li>
<code>EXPR || EXPR</code>: Much like the ‘-o’ operator of test, but
does not evaluate the second expression if the first already turns out
to be true.
</li>
<li>
Numeric operators:
<ul>
<li>
<code>INT -eq INT</code>: True if both integers are equal.
</li>
<li>
<code>INT -ne INT</code>: True if the integers are not equal.
</li>
<li>
<code>INT -lt INT</code>: True if the first integer is less than
the second.
</li>
<li>
<code>INT -gt INT</code>: True if the first integer is greater
than the second.
</li>
<li>
<code>INT -le INT</code>: True if the first integer is less than
or equal to the second.
</li>
<li>
<code>INT -ge INT</code>: True if the first integer is greater
than or equal to the second.
</li>
</ul>
</li>
</ul>
<p>You might occasionally come across something like this:</p>
<pre>
<code>[ a = b ]</code>
</pre>
<p>
Here, we use single brackets instead of double brackets. This is, in
fact, an entirely different command, the <code>[</code> command or{" "}
<em>old test command</em>. It has the same purpose–comparing things–but
the <code>[[</code> command is newer, has more features, and is easier
to use. We strongly recommend using <code>[[</code> over <code>[</code>.
</p>
<h2 data-number="6.4" id="conditional-loops-while-until-and-for">
<span className="header-section-number">6.4</span> Conditional Loops
(while, until and for)
</h2>
<p>
Loops can be used to repeat a list of commands multiple times. In bash,
there are <code>while</code> loops and <code>for</code> loops.
</p>
<p>While loops look like this:</p>
<pre>
<code>
while true{"\n"}do{"\n"}
{" "}echo 'Infinite loop'{"\n"}done
</code>
</pre>
<p>
The <code>while</code> keyword will execute the <code>true</code>{" "}
command, and if that returns 0, it executes all commands between the{" "}
<code>do</code> and <code>done</code>. After that, it starts over, until
the <code>true</code> command returns 1 (which it never does, which is
why this loop will run indefinitely).
</p>
<p>
The above example might not be immediately useful, but you could also do
something like this:
</p>
<pre>
<code>
while ping -c 1 -W 1 www.google.com{"\n"}do{"\n"}
{" "}echo 'Google still works!'{"\n"}done
</code>
</pre>
<p>
There’s also a variation of the <code>while</code> loop, called{" "}
<code>until</code>. It works similarly, except it only runs its command
list when the first command <em>fails</em>:
</p>
<pre>
<code>
until ping -c 1 -W 1 www.google.com{"\n"}do{"\n"}
{" "}echo 'Google isn'\''t working!'{"\n"}done
</code>
</pre>
<p>
<code>for</code> loops can be used to iterate over a list of strings:
</p>
<pre>
<code>
for var in 1 2 3{"\n"}do{"\n"}
{" "}echo "$var"{"\n"}done
</code>
</pre>
<p>
After the <code>for</code>, you specify a variable name. After the{" "}
<code>in</code>, you list all the strings you want to iterate over.
</p>
<p>
The loop works by setting the variable you specified to all the values
from the list in turn, and then executing the command list for each of
them.
</p>
<p>
This is especially useful in combination with globs or brace expansions:
</p>
<pre>
<code>
echo 'This is a list of all my files starting with f:'{"\n"}for var in
f*
{"\n"}do{"\n"}
{" "}echo "$var"{"\n"}done{"\n"}
{"\n"}echo 'And now I will count from 1 to 100:'{"\n"}for var in {"{"}
1..100{"}"}
{"\n"}do{"\n"}
{" "}echo "$var"{"\n"}done
</code>
</pre>
<h2 data-number="6.5" id="choices-case-and-select">
<span className="header-section-number">6.5</span> Choices (case and
select)
</h2>
<p>
Sometimes, you want your script to behave differently depending on the
content of a variable. This could be implemented by taking a different
branch of an if statement for each state:
</p>
<pre>
<code>
if [[ "$LANG" = 'en' ]]{"\n"}then{"\n"}
{" "}echo 'Hello!'{"\n"}elif [[ "$LANG" = 'de' ]]{"\n"}then{"\n"}
{" "}echo 'Guten Tag!'{"\n"}elif [[ "$LANG" = 'it' ]]{"\n"}then
{"\n"}
{" "}echo 'Ciao!'{"\n"}else{"\n"}
{" "}echo 'I do not speak your language.'{"\n"}fi
</code>
</pre>
<p>
This is quite cumbersome to write. At the same time, constructs like
this are very common. For that reason, bash provides a keyword to
simplify it:
</p>
<pre>
<code>
case "$LANG" in{"\n"}
{" "}en){"\n"}
{" "}echo 'Hello!'{"\n"}
{" "};;{"\n"}
{" "}de) {"\n"}
{" "}echo 'Guten Tag!'{"\n"}
{" "};;{"\n"}
{" "}it){"\n"}
{" "}echo 'Ciao!'{"\n"}
{" "};;{"\n"}
{" "}*){"\n"}
{" "}echo 'I do not speak your language.'{"\n"}
{" "};;{"\n"}esac
</code>
</pre>
<p>
Each choice of the case statement consists of a string or glob pattern,
a <code>)</code>, a list of commands that is to be executed if the
string matches the pattern, and two semicolons to denote the end of a
list of commands.
</p>
<p>
The string after the keyword <code>case</code> is matched against each
glob pattern in order. The list of commands after the first match is
executed. After that, execution continues after the <code>esac</code>.
</p>
<p>
Since the string is matched against glob patterns, we can use{" "}
<code>*</code> in the end to catch anything that didn’t match before.
</p>
<p>
Another construct of choice is the <code>select</code> construct. It
looks and works similarly to a loop, but it also presents the user with
a predefined choice. You are encouraged to try running this example
yourself:
</p>
<pre>
<code>
echo 'Which one of these does not belong in the group?'{"\n"}select
choice in Apples Pears Crisps Lemons Kiwis{"\n"}do{"\n"}
{" "}if [[ "$choice" = Crisps ]]{"\n"}
{" "}then{"\n"}
{" "}echo 'Correct! Crisps are not fruit.'{"\n"}
{" "}break{"\n"}
{" "}fi{"\n"}
{" "}echo 'Wrong answer. Try again.'{"\n"}done
</code>
</pre>
<p>
The syntax of the <code>select</code> construct is very similar to{" "}
<code>for</code> loops. The difference is that instead of setting the
variable (<code>choice</code> in this example) to each value in turn,
the <code>select</code> construct lets the user choose which value is
used next. This also means that a <code>select</code> construct can run
indefinitely, because the user can keep selecting new choices. To avoid
being trapped in it, we have to explicitly use <code>break</code>.{" "}
<code>break</code> is a builtin command that makes bash jump out of the
current <code>do</code> block. Execution will continue after the{" "}
<code>done</code>. <code>break</code> also works in <code>for</code> and{" "}
<code>while</code> loops.
</p>
<p>
As you can see in the example above, we used an <code>if</code> command
inside a <code>select</code> command. All of these conditional
constructs (<code>if</code>, <code>for</code>, <code>while</code>,{" "}
<code>case</code> and <code>select</code>) can be nested indefinitely.
</p>
<h1 data-number={7} id="input-and-output">
<span className="header-section-number">7</span> Input and Output
</h1>
<p>
Input and output in bash is very flexible and, consequentially, complex.
We will only look at the most widely used components.
</p>
<h2 data-number="7.1" id="command-line-arguments">
<span className="header-section-number">7.1</span> Command-line
Arguments
</h2>
<p>
For many bash scripts, the first input we care about are the arguments
given to it via the command line. As we saw in the chapter on
Parameters, these arguments are contained in some{" "}
<em>special parameters</em>. These are called{" "}
<em>positional parameters</em>. The first parameter is referred to with{" "}
<code>$1</code>, the second with <code>$2</code>, and so on. After
number 9, you have to enclose the numbers in curly braces:{" "}
<code>
${"{"}10{"}"}
</code>
,{" "}
<code>
${"{"}11{"}"}
</code>{" "}
and so on.
</p>
<p>
In addition to referring to them one at a time, you may also refer to
the entire set of positional parameters with the <code>"$@"</code>{" "}
substitution. The double quotes here are{" "}
<strong>extremely important</strong>. If you don’t use the double
quotes, each one of the positional parameters will undergo word
splitting and globbing. You don’t want that. By using the quotes, you
tell Bash that you want to preserve each parameter as a separate word.
</p>
<p>
There are even more ways to deal with parameters. For example, it is
very common for commands to accept <em>options</em>, which are single
letters starting with a <code>-</code>. For example, <code>ls -l</code>{" "}
calls the <code>ls</code> program with the <code>-l</code> option, which
makes it output more information. Usually, multiple options can be
combined, as in <code>ls -la</code>, which is equivalent to{" "}
<code>ls -l -a</code>.
</p>
<p>
You might want to create your own scripts that accept some options. Bash
has the so called <code>getopts</code> builtin command to parse passed
options.
</p>
<pre>
<code>
while getopts 'hlf:' opt{"\n"}do {"\n"}
{" "}case "$opt" in{"\n"}
{" "}h|\?){"\n"}
{" "}echo 'available options: -h -l -f [filename]'{"\n"}
{" "};;{"\n"}
{" "}f){"\n"}
{" "}file="$OPTARG"{"\n"}
{" "};;{"\n"}
{" "}l){"\n"}
{" "}list=true{"\n"}
{" "};;{"\n"}
{" "}esac{"\n"}done{"\n"}
{"\n"}shift "$(( OPTIND - 1 ))"
</code>
</pre>
<p>
As you can see, we use <code>getopts</code> within a while loop.{" "}
<code>getopts</code> will return 0 as long as there are more options
remaining and something else if there are no more options. That makes it
perfectly suitable for a loop.
</p>
<p>
<code>getopts</code> takes two arguments, the <em>optstring</em> and the{" "}
<em>variable name</em>. The optstring contains all the letters that are
valid options. In our example, these are <code>h</code>, <code>l</code>{" "}
and <code>f</code>.
</p>
<p>
The <code>f</code> is followed by a colon. This indicates that the f
option requires an argument. The script could for example be called like
so:
</p>
<pre>
<code>myscript -f file.txt</code>
</pre>
<p>
<code>getopts</code> will set the variable that you specified as its
second argument to the letter of the option it found first. If the
option required an argument, the variable <code>OPTARG</code> is set to
whatever the argument was. In the example above, a case statement is
used to react to the different options.
</p>
<p>
There’s also a special option <code>?</code>. Whenever{" "}
<code>getopts</code> finds an option that is not present in the
optstring, it sets the shell variable (<code>opt</code> in the example)
to <code>?</code>. In the case statement above, that triggers the help
message.
</p>
<p>
After all options are parsed, the remaining arguments are “moved” such
that they are now in <code>$1</code>, <code>$2</code>… even though
previously, these positional parameters were occupied by the options.
</p>
<p>
Also note the line <code>shift "$(( OPTIND - 1 ))"</code> at the end.
The <code>shift</code> builtin can be used to discard command-line
arguments. Its argument is a number and designates how many arguments we
want to discard.
</p>
<p>
This is needed because we don’t know how many options the user will pass
to our script. If there are more positional parameters after all the
options, we have no way of knowing at which number they start.
Fortunately, <code>getopts</code> also sets the shell variable{" "}
<code>OPTIND</code>, in which it stores the index of the option it’s
going to parse next.
</p>
<p>
So after parsing all the option, we just discard the first{" "}
<code>OPTIND - 1</code> options, and the remaining arguments now start
from <code>$1</code> onwards.
</p>
<h2 data-number="7.2" id="file-descriptors">
<span className="header-section-number">7.2</span> File Descriptors
</h2>
<p>
<em>File descriptors</em> are the way programs refer to files, or other
things that work like files (such as pipes, devices, or terminals). You
can think of them as pointers that point to data locations. Through
these pointers, programs can write to or read from these locations.
</p>
<p>By default, every program has three file descriptors:</p>
<ul>
<li>Standard Input (stdin): File Descriptor 0</li>
<li>Standard Output (stdout): File Descriptor 1</li>
<li>Standard Error (stderr): File Descriptor 2</li>
</ul>
<p>
When you run a script in the terminal, then stdin contains everything
you type in that terminal. stdout and stderr both point to the terminal,
and everything that is written to these two is displayed as text in the
terminal. stdout is where programs send their normal information, and
stderr is where they send their error messages.
</p>
<p>
Let’s make these definitions a little more concrete. Consider this
example:
</p>
<pre>
<code>
echo 'What is your name?'{"\n"}read name{"\n"}echo "Good day, $name.
Would you like some tea?"
</code>
</pre>
<p>
You already know <code>echo</code>. It simply prints its argument to{" "}
<em>stdout</em>. Since stdout is connected to your terminal, you will
see that message there.
</p>
<p>
<code>read</code> is a command that reads one line of text from{" "}
<em>stdin</em> and stores it in a variable, which we specified to be{" "}
<code>name</code>. Because stdin is connected to what you type in your
terminal, it will let you type a line of text, and as soon as you press
enter, that line will be stored in the variable.
</p>
<p>So what about stderr? Consider this example:</p>
<pre>
<code>ehco 'Hello!'</code>
</pre>
<p>
The command <code>ehco</code> does not exist. If you run this, bash will
print an error message to <em>stderr</em>. Because stderr is connected
to your terminal, you will see that message there.
</p>
<h2 data-number="7.3" id="redirection">
<span className="header-section-number">7.3</span> Redirection
</h2>
<p>
<em>Redirection</em> is the most basic form of input/output manipulation
in bash. It is used to change the source or destination of{" "}
<em>File descriptors</em>, i.e. connect them to something other
than your terminal. For example, you can send a command’s output to a
file instead.
</p>
<pre>
<code>
echo 'It was a dark and stormy night. Too dark to write.' > story
</code>
</pre>
<p>
The <code>></code> operator begins an <em>output redirection</em>. It
redirects the <em>stdout</em> file descriptor of the command to the
left, and connects it to a file called “story”. That means if you run
this, you will not see the output of <code>echo</code>—after all, stdout
no longer points to your terminal.
</p>
<p>
Note that <code>></code> will just open the file you specify without
checking whether it already exists first. If the file already exists,
its contents will be overwritten and you will lose whatever was stored
in there before. <strong>Be careful.</strong>
</p>
<p>
If you don’t want to overwrite the existing content of a file, but
rather append your output to the end of that file, you can use{" "}
<code>>></code> instead of <code>></code>.
</p>
<p>
Now, let’s look at <em>input redirection</em>. For that, we first
introduce a command named <code>cat</code>. <code>cat</code> is often
used to display the contents of a file, like so:
</p>
<pre>
<code>cat myfile</code>
</pre>
<p>
If <code>cat</code> is called without an argument, however, it will
simply read from <em>stdin</em> and print that directly to{" "}
<em>stdout</em>.
</p>
<p>
Try the following: Run <code>cat</code>, without arguments, in your
terminal. Then type some characters and hit enter. Can you figure out
what is happening?
</p>
<p>
<em>Input redirection</em> uses the <code><</code> operator. It works
as follows:
</p>
<pre>
<code>cat < story</code>
</pre>
<p>
The <code><</code> operator will take a command’s <em>stdin</em> file
descriptor and point it to a file, “story” in this example. This means{" "}
<code>cat</code> now ignores your terminal and reads from “story”
instead. Note that this has the same effect as typing{" "}
<code>cat story</code>.
</p>
<p>
If you want to redirect <em>stderr</em> instead of <em>stdout</em>, you
can do as follows:
</p>
<pre>
<code>ehco 'Hello!' 2> errors</code>
</pre>
<p>
If you run this, you won’t see any error message, even though the
command <code>ehco</code> doesn’t exist. That’s because <em>stderr</em>{" "}
is no longer connected to your terminal, but to a file called “errors”
instead.
</p>
<p>
Now that you know about redirection, there is one subtlety that you have
to be aware of: You can’t have two file descriptors point to the same
file.
</p>
<p>
If you wanted to log a command’s complete output–stdout <em>and</em>{" "}
stderr–you might be tempted to do something like this:
</p>
<pre>
<code>mycommand > logfile 2> logfile</code>
</pre>
<p>
However, this is a <strong>bad</strong> idea. The two file descriptors
will now both point to the same file <em>independently</em>, which
causes them to constantly overwrite each other’s text.
</p>
<p>
If you still want to point both stdout and stderr to the same file, you
can do it like this:
</p>
<pre>
<code>mycommand > logfile 2>&1</code>
</pre>
<p>
Here, we use the <code>>&</code> syntax to duplicate file
descriptor 1. In this scenario, we no longer have two file descriptors
pointing to one file. Instead, we have only one file descriptor that
acts as both stdout and stderr at the same time.
</p>
<p>
To help remember the syntax, you can think of <code>&1</code> as
“where 1 is”, and of the <code>2></code> as “point 2 to”. The whole
thing, <code>2>&1</code>, then becomes “point 2 to wherever 1
is”. This also makes it clear that <code>> logfile</code> has to come{" "}
<em>before</em> <code>2>&1</code>: First you point 1 to
“logfile”, and only then you can point 2 to where 1 is.
</p>
<p>
There’s also a quick way to completely get rid of a command’s output
using redirections. Consider this:
</p>
<pre>
<code>mycommand > /dev/null 2>&1</code>
</pre>
<p>
<code>/dev/null</code> is a special file in your file system that you
can write to, but the things you write to it are not stored. So,{" "}
<code>mycommand</code>’s output is written somewhere where it’s not
stored or processed in any way. It is discarded completely.
</p>
<p>
You could also leave out the <code>2>&1</code>. Then, you’d still
see error messages, but discard the normal output.
</p>
<h2 data-number="7.4" id="pipes">
<span className="header-section-number">7.4</span> Pipes
</h2>
<p>
Now that you know how to manipulate <em>file descriptors</em> to direct
output to files, it’s time to learn another type of I/O redirection.
</p>
<p>
The <code>|</code> operator can be used to connect one command’s{" "}
<em>stdout</em> to another command’s <em>stdin</em>. Have a look at
this:
</p>
<pre>
<code>echo 'This is a beautiful day!' | sed 's/beauti/wonder'</code>
</pre>
<p>
The <code>sed</code> command (“sed” is short for “stream editor”) is a
utility that can be used to manipulate text “on the fly”. It reads text
from stdin, edits it according to some commands, and then prints the
result to stdout. It is very powerful. Here, we use it to replace
“beauti” with “wonder”.
</p>
<p>
First, the <code>echo</code> command writes some text to it’s stdout.
The <code>|</code> operator connected <code>echo</code>’s stout to{" "}
<code>sed</code>’s stdin, so everything <code>echo</code> sends there is
immediately picked up by <code>sed</code>. <code>sed</code> will then
edit the text and print the result to its own stdout. <code>sed</code>’s
stdout is still connected to your terminal, so this is what you see.
</p>
<h1 data-number={8} id="compound-commands">
<span className="header-section-number">8</span> Compound Commands
</h1>
<p>
<em>Compound commands</em> is a catch-all phrase covering several
different concepts. We’ve already seen <code>if</code>, <code>for</code>
, <code>while</code>, <code>case</code>, <code>select</code> and the{" "}
<code>[[</code> keyword, which all fall into this category. Now we’ll
look at a few more.
</p>
<h2 data-number="8.1" id="subshells">
<span className="header-section-number">8.1</span> Subshells
</h2>
<p>
<em>Subshells</em> can be used to encapsulate a command’s effect. If a
command has undesired side effects, you can execute it in a subshell.
Once the subshell command ends, all side effects will be gone.
</p>
<p>
To execute a command (or several commands) in a subshell, enclose them
in parenthesis:
</p>
<pre>
<code>
( {"\n"}
{" "}cd /tmp {"\n"}
{" "}pwd{"\n"}){"\n"}pwd
</code>
</pre>
<p>
The <code>cd</code> and the first <code>pwd</code> commands are executed
in a subshell. All side effects in that subshell won’t affect the second{" "}
<code>pwd</code> command. Changing the current directory is such a side
effect–even though we use <code>cd</code> to go to the <code>/tmp</code>{" "}
folder, we jump back to our original folder as soon as the subshell
ends.
</p>
<h2 data-number="8.2" id="command-grouping">
<span className="header-section-number">8.2</span> Command Grouping
</h2>
<p>
You can group several commands together by enclosing them in curly
braces. This makes bash consider them as a unit with regard to pipes,
redirections and control flow:
</p>
<pre>
<code>
{"{"}
{"\n"}
{" "}echo 'Logfile of my backup'{"\n"}
{" "}rsync -av . /backup{"\n"}
{" "}echo "Backup finished with exit code $#"{"\n"}
{"}"} > backup.log 2>&1
</code>
</pre>
<p>
This redirects stdout and stderr of <em>all three commands</em> to a
file called backup.log. Note that while this looks similar to subshells,
it is not the same. Side effects that happen within the curly braces
will still be present outside of them.
</p>
<h2 data-number="8.3" id="arithmetic-evaluation">
<span className="header-section-number">8.3</span> Arithmetic Evaluation
</h2>
<p>
So far, we’ve only been manipulating strings in bash. Sometimes, though,
it is also necessary to manipulate numbers. This is done through
arithmetic evaluation.
</p>
<p>
Say you want to add the numbers 5 and 4. You might do something like
this:
</p>
<pre>
<code>a=5+4</code>
</pre>
<p>
However, this will result in the variable <code>a</code> containing the
string <code>5+4</code>, rather than the number <code>9</code>. Instead,
you should do this:
</p>
<pre>
<code>(( a=5+4 ))</code>
</pre>
<p>
The double parenthesis indicate that something arithmetic is happening.
In fact, <code>((</code> is a bash keyword, much like <code>[[</code>.
</p>
<p>
<code>((</code> can also be used to do arithmetic comparison:
</p>
<pre>
<code>
if (( 5 > 9 )){"\n"}then{"\n"}
{" "}echo '5 is greater than 9'{"\n"}else {"\n"}
{" "}echo '5 is not greater than 9'{"\n"}fi
</code>
</pre>
<p>
It is important not to confuse <code>((</code> and <code>[[</code>.{" "}
<code>[[</code> is for comparing strings (among other things), while{" "}
<code>((</code> is only for comparing numbers.
</p>
<p>
There’s also <em>arithmetic substitution</em>, which works similarly to{" "}
<em>command substitution</em>:
</p>
<pre>
<code>echo "There are $(( 60 * 60 * 24 )) seconds in a day."</code>
</pre>
<h1 data-number={9} id="functions">
<span className="header-section-number">9</span> Functions
</h1>
<p>
Inside a bash script, functions are very handy. They are lists of
commands–much like a normal script–except they don’t reside in their own
file. They do however take arguments, just like scripts.
</p>
<p>Functions can be defined like this:</p>
<pre>
<code>
sum() {"{"}
{"\n"}
{" "}echo "$1 + $2 = $(( $1 + $2 ))"{"\n"}
{"}"}
</code>
</pre>
<p>
If you put this in a script file and run it, absolutely nothing will
happen. The function <code>sum</code> has been defined, but it is never
used.
</p>
<p>
You can use your function like any other command, but you have to define
it <em>before</em> you use it:
</p>
<pre>
<code>
sum() {"{"}
{"\n"}
{" "}echo "$1 + $2 = $(( $1 + $2 ))"{"\n"}
{"}"}
{"\n"}sum 1 2{"\n"}sum 3 9{"\n"}sum 6283 3141
</code>
</pre>
<p>
As you can see, you can use the function <code>sum</code> multiple
times, but you only need to define it once. This is useful in larger
scripts, where a certain task has to be performed multiple times.
Whenever you catch yourself writing the same or very similar code twice
in the same script, you should consider using a function.
</p>
<h1 data-number={10} id="useful-commands">
<span className="header-section-number">10</span> Useful Commands
</h1>
<p>
This chapter provides an overview of useful commands that you can use in
your scripts. It is nowhere near complete, and serves only to provide a
brief overview. If you want to know more about a specific command, you
should read its manpage.
</p>
<p>
<strong>grep</strong>
</p>
<p>
<code>grep</code> can be used to search for a string within a file, or
within the output of a command.
</p>
<pre>
<code>
# searches logfile.txt for lines containing the word error{"\n"}grep
'error' logfile.txt{" "}
{"\n"}
{"\n"}# searches the directory 'folder' for files {"\n"}# containing
the word 'analysis'{"\n"}grep 'analysis' folder/{" "}
{"\n"}
{"\n"}# searches the output of 'xrandr' for lines that say
'connected'. {"\n"}# only matches whole words, so 'disconnected' will
not match.{"\n"}
xrandr | grep -w 'connected'{" "}
</code>
</pre>
<p>
<code>grep</code> returns 0 if it finds something, and returns an error
if it doesn’t. This makes it useful for conditionals.
</p>
<p>
<strong>sed</strong>
</p>
<p>
<code>sed</code> can be used to edit text “on the fly”. It uses its own
scripting language to describe modifications to be made to the text,
which makes it extremely powerful. Here, we provide examples for the
most common usages of sed:
</p>
<pre>
<code>
# replaces the first occurrence of 'find' in every line by 'replace'
{"\n"}
sed 's/find/replace' inputfile {"\n"}
{"\n"}# replaces every occurrence of 'find' in every line by 'replace'
{"\n"}sed 's/find/replace/g' inputfile {"\n"}
{"\n"}# deletes the first occurrence of 'find' in every line{"\n"}sed
's/find//' inputfile {"\n"}
{"\n"}# deletes every occurrence of 'find' in every line{"\n"}sed
's/find//g' inputfile {"\n"}
{"\n"}# displays only the 12th line{"\n"}sed '12q;d' inputfile{" "}
</code>
</pre>
<p>
<code>sed</code> is often used in combination with pipes to format the
output or get rid of unwanted characters.
</p>
<p>
<strong>curl and wget</strong>
</p>
<p>
<code>curl</code> and <code>wget</code> are two commands that can be
used to access websites or other content from the web. The difference is
that <code>wget</code> will simply download the content to a file, while{" "}
<code>curl</code> will output it to the console.
</p>
<pre>
<code>
curl http://www.thealternative.ch{"\n"}wget
http://files.project21.ch/LinuxDays-Public/16FS-install-guide.pdf
</code>
</pre>
<p>
<strong>xrandr</strong>
</p>
<p>
<code>xrandr</code> can be used to manipulate your video outputs,
i.e. enabling and disabling monitors or setting their screen
resolution and orientation.
</p>
<pre>
<code>
# list all available outputs and their status info{"\n"}xrandr{" "}
{"\n"}
{"\n"}# enables output HDMI-1{"\n"}xrandr --output HDMI-1 --auto{" "}
{"\n"}
{"\n"}# puts output HDMI-1 to the left of output LVDS-1{"\n"}xrandr
--output HDMI-1 --left-of LVDS-1 {"\n"}
{"\n"}# disables output LVDS-1{"\n"}xrandr --output LVDS-1 --off{" "}
</code>
</pre>
<p>
<strong>ImageMagick (convert)</strong>
</p>
<p>
The <code>convert</code> command makes it possible to do image
processing from the commandline.
</p>
<pre>
<code>
# scale fullHDWallpaper.jpg to specified resolution{"\n"}convert
fullHDWallpaper.jpg -scale 3200x1800 evenBiggerWallpaper.jpg {"\n"}
{"\n"}# "automagically" adjusts the gamma level of somePicture.jpg
{"\n"}
convert somePicture.jpg -auto-gamma someOtherPicture.jpg {"\n"}
{"\n"}# transform image to black and white{"\n"}convert
colorfulPicture.jpg -monochrome blackWhitePicture.jpg{" "}
</code>
</pre>
<p>
It is extremely powerful and has lots of options. A good resource is the{" "}
<a href="http://www.imagemagick.org">official website</a>. It also
provides examples for most options.
</p>
<p>
<strong>notify-send</strong>
</p>
<p>
<code>notify-send</code> can be used to display a desktop notification
with some custom text:
</p>
<pre>
<code>
notify-send 'Battery warning' 'Your battery level is below 10%'
</code>
</pre>
<p>
The first argument is the notification’s title, the second is its
description.
</p>
<p>
<code>notify-send</code> requires a <em>notification daemon</em> to be
running, else it won’t work. Most desktop environments come with a
notification daemon set up and running. If you can’t see your
notifications, it might be that you don’t have such a daemon.
</p>
<p>
<strong>find</strong>
</p>
<p>
<code>find</code> can be used to find files in a directory structure.
</p>
<pre>
<code>
# finds all files in the current directory and all subdirectories that
end
{"\n"}# in .png{"\n"}find -name '*.png' {"\n"}
{"\n"}# finds all files ending in .tmp and removes them. {"{"}
{"}"} is replaced by the{"\n"}# file's name when executing the
command.
{"\n"}# Note that we don't use globbing here, but instead pass the *
to find.{"\n"}# find will then interpret the * as a wildcard.{"\n"}
find -name '*.tmp' -exec rm '{"{"}
{"}"}'{"\n"}
{"\n"}# finds all files in the directory 'files' and prints their size
and path{"\n"}find 'files/' -printf '%s %p\n'{" "}
</code>
</pre>
<p>
<code>find</code> has many options that allow you to perform arbitrary
actions on the files it found or pretty-print the output.
</p>
<p>
<strong>sort</strong>
</p>
<p>
<code>sort</code> sorts lines of text files, or lines it reads from{" "}
<em>stdin</em>.
</p>
<pre>
<code>
sort listOfNames.txt # sorts all lines in listOfNames.txt
alphabetically
</code>
</pre>
<p>
<strong>head and tail</strong>
</p>
<p>
<code>head</code> and <code>tail</code> can be used to show the
beginning or the end of a long stream of text, respectively.
</p>
<pre>
<code>
# display the last few lines of the dmesg log{"\n"}dmesg | tail {"\n"}
{"\n"}# display only the first few lines of a very long text file
{"\n"}
head verylongtext.txt{" "}
</code>
</pre>
<p>
<strong>jshon</strong>
</p>
<p>
<code>jshon</code> is a very simple command-line json parser. It can
read data in json format and return specific values.
</p>
<p>
Its most important options are <code>-e</code> and <code>-a</code>.{" "}
<code>-e</code> extracts the value of a given key from a json array or
object:
</p>
<pre>
<code>
# Find the object with key "title" from a json object stored in the
file "json"{"\n"}jshon -e 'title' < 'json'
</code>
</pre>
<p>
The <code>-a</code> option maps all remaining options across the
currently selected element. It has to be combined with other options,
for example the <code>-e</code> option.
</p>
<pre>
<code>
# Find the names of all elements stored in the json object in file
"json"
{"\n"}jshon -a -e 'name' < 'json'
</code>
</pre>
<p>
<strong>shuf</strong>
</p>
<p>
<code>shuf</code> randomly permutates the lines of its input,
effectively <em>shuffling</em> them.
</p>
<pre>
<code>
# Shuffle the lines of file "playlist"{"\n"}shuf 'playlist'{"\n"}
{"\n"}# Get a random line from file "quotes"{"\n"}shuf -n 1 'quotes'
</code>
</pre>
<p>
<strong>tee</strong>
</p>
<p>
<code>tee</code> takes input from <em>stdin</em> and writes it to a
file:
</p>
<pre>
<code>sudo zypper up | tee 'updatelog'</code>
</pre>
<p>Note that this is equivalent to</p>
<pre>
<code>sudo zypper up > 'updatelog'</code>
</pre>
<p>
<code>tee</code> is useful when you want to write to a file that
requires root access. Then you can do the following:
</p>
<pre>
<code>echo 'some configuration' | sudo tee '/etc/systemconfig'</code>
</pre>
<p>
A normal redirection wouldn’t work in this case, as that would open the
file as a normal user instead of root.{" "}
<strong>Please be careful when modifying system files.</strong>
</p>
<p>
<strong>sleep</strong>
</p>
<p>