├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE.md └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── NOTICE ├── README.md ├── Snippets.md └── Solutions ├── fortune ├── multigame └── sysreport /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # Codeowners for these exercise files: 2 | # * (asterisk) deotes "all files and folders" 3 | # Example: * @producer @instructor 4 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 7 | 8 | ## Issue Overview 9 | 10 | 11 | ## Describe your environment 12 | 13 | 14 | ## Steps to Reproduce 15 | 16 | 1. 17 | 2. 18 | 3. 19 | 4. 20 | 21 | ## Expected Behavior 22 | 23 | 24 | ## Current Behavior 25 | 26 | 27 | ## Possible Solution 28 | 29 | 30 | ## Screenshots / Video 31 | 32 | 33 | ## Related Issues 34 | 35 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | .tmp 4 | npm-debug.log 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 2 | Contribution Agreement 3 | ====================== 4 | 5 | This repository does not accept pull requests (PRs). All pull requests will be closed. 6 | 7 | However, if any contributions (through pull requests, issues, feedback or otherwise) are provided, as a contributor, you represent that the code you submit is your original work or that of your employer (in which case you represent you have the right to bind your employer). By submitting code (or otherwise providing feedback), you (and, if applicable, your employer) are licensing the submitted code (and/or feedback) to LinkedIn and the open source community subject to the BSD 2-Clause license. 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | LinkedIn Learning Exercise Files License Agreement 2 | ================================================== 3 | 4 | This License Agreement (the "Agreement") is a binding legal agreement 5 | between you (as an individual or entity, as applicable) and LinkedIn 6 | Corporation (“LinkedIn”). By downloading or using the LinkedIn Learning 7 | exercise files in this repository (“Licensed Materials”), you agree to 8 | be bound by the terms of this Agreement. If you do not agree to these 9 | terms, do not download or use the Licensed Materials. 10 | 11 | 1. License. 12 | - a. Subject to the terms of this Agreement, LinkedIn hereby grants LinkedIn 13 | members during their LinkedIn Learning subscription a non-exclusive, 14 | non-transferable copyright license, for internal use only, to 1) make a 15 | reasonable number of copies of the Licensed Materials, and 2) make 16 | derivative works of the Licensed Materials for the sole purpose of 17 | practicing skills taught in LinkedIn Learning courses. 18 | - b. Distribution. Unless otherwise noted in the Licensed Materials, subject 19 | to the terms of this Agreement, LinkedIn hereby grants LinkedIn members 20 | with a LinkedIn Learning subscription a non-exclusive, non-transferable 21 | copyright license to distribute the Licensed Materials, except the 22 | Licensed Materials may not be included in any product or service (or 23 | otherwise used) to instruct or educate others. 24 | 25 | 2. Restrictions and Intellectual Property. 26 | - a. You may not to use, modify, copy, make derivative works of, publish, 27 | distribute, rent, lease, sell, sublicense, assign or otherwise transfer the 28 | Licensed Materials, except as expressly set forth above in Section 1. 29 | - b. Linkedin (and its licensors) retains its intellectual property rights 30 | in the Licensed Materials. Except as expressly set forth in Section 1, 31 | LinkedIn grants no licenses. 32 | - c. You indemnify LinkedIn and its licensors and affiliates for i) any 33 | alleged infringement or misappropriation of any intellectual property rights 34 | of any third party based on modifications you make to the Licensed Materials, 35 | ii) any claims arising from your use or distribution of all or part of the 36 | Licensed Materials and iii) a breach of this Agreement. You will defend, hold 37 | harmless, and indemnify LinkedIn and its affiliates (and our and their 38 | respective employees, shareholders, and directors) from any claim or action 39 | brought by a third party, including all damages, liabilities, costs and 40 | expenses, including reasonable attorneys’ fees, to the extent resulting from, 41 | alleged to have resulted from, or in connection with: (a) your breach of your 42 | obligations herein; or (b) your use or distribution of any Licensed Materials. 43 | 44 | 3. Open source. This code may include open source software, which may be 45 | subject to other license terms as provided in the files. 46 | 47 | 4. Warranty Disclaimer. LINKEDIN PROVIDES THE LICENSED MATERIALS ON AN “AS IS” 48 | AND “AS AVAILABLE” BASIS. LINKEDIN MAKES NO REPRESENTATION OR WARRANTY, 49 | WHETHER EXPRESS OR IMPLIED, ABOUT THE LICENSED MATERIALS, INCLUDING ANY 50 | REPRESENTATION THAT THE LICENSED MATERIALS WILL BE FREE OF ERRORS, BUGS OR 51 | INTERRUPTIONS, OR THAT THE LICENSED MATERIALS ARE ACCURATE, COMPLETE OR 52 | OTHERWISE VALID. TO THE FULLEST EXTENT PERMITTED BY LAW, LINKEDIN AND ITS 53 | AFFILIATES DISCLAIM ANY IMPLIED OR STATUTORY WARRANTY OR CONDITION, INCLUDING 54 | ANY IMPLIED WARRANTY OR CONDITION OF MERCHANTABILITY OR FITNESS FOR A 55 | PARTICULAR PURPOSE, AVAILABILITY, SECURITY, TITLE AND/OR NON-INFRINGEMENT. 56 | YOUR USE OF THE LICENSED MATERIALS IS AT YOUR OWN DISCRETION AND RISK, AND 57 | YOU WILL BE SOLELY RESPONSIBLE FOR ANY DAMAGE THAT RESULTS FROM USE OF THE 58 | LICENSED MATERIALS TO YOUR COMPUTER SYSTEM OR LOSS OF DATA. NO ADVICE OR 59 | INFORMATION, WHETHER ORAL OR WRITTEN, OBTAINED BY YOU FROM US OR THROUGH OR 60 | FROM THE LICENSED MATERIALS WILL CREATE ANY WARRANTY OR CONDITION NOT 61 | EXPRESSLY STATED IN THESE TERMS. 62 | 63 | 5. Limitation of Liability. LINKEDIN SHALL NOT BE LIABLE FOR ANY INDIRECT, 64 | INCIDENTAL, SPECIAL, PUNITIVE, CONSEQUENTIAL OR EXEMPLARY DAMAGES, INCLUDING 65 | BUT NOT LIMITED TO, DAMAGES FOR LOSS OF PROFITS, GOODWILL, USE, DATA OR OTHER 66 | INTANGIBLE LOSSES . IN NO EVENT WILL LINKEDIN'S AGGREGATE LIABILITY TO YOU 67 | EXCEED $100. THIS LIMITATION OF LIABILITY SHALL: 68 | - i. APPLY REGARDLESS OF WHETHER (A) YOU BASE YOUR CLAIM ON CONTRACT, TORT, 69 | STATUTE, OR ANY OTHER LEGAL THEORY, (B) WE KNEW OR SHOULD HAVE KNOWN ABOUT 70 | THE POSSIBILITY OF SUCH DAMAGES, OR (C) THE LIMITED REMEDIES PROVIDED IN THIS 71 | SECTION FAIL OF THEIR ESSENTIAL PURPOSE; AND 72 | - ii. NOT APPLY TO ANY DAMAGE THAT LINKEDIN MAY CAUSE YOU INTENTIONALLY OR 73 | KNOWINGLY IN VIOLATION OF THESE TERMS OR APPLICABLE LAW, OR AS OTHERWISE 74 | MANDATED BY APPLICABLE LAW THAT CANNOT BE DISCLAIMED IN THESE TERMS. 75 | 76 | 6. Termination. This Agreement automatically terminates upon your breach of 77 | this Agreement or termination of your LinkedIn Learning subscription. On 78 | termination, all licenses granted under this Agreement will terminate 79 | immediately and you will delete the Licensed Materials. Sections 2-7 of this 80 | Agreement survive any termination of this Agreement. LinkedIn may discontinue 81 | the availability of some or all of the Licensed Materials at any time for any 82 | reason. 83 | 84 | 7. Miscellaneous. This Agreement will be governed by and construed in 85 | accordance with the laws of the State of California without regard to conflict 86 | of laws principles. The exclusive forum for any disputes arising out of or 87 | relating to this Agreement shall be an appropriate federal or state court 88 | sitting in the County of Santa Clara, State of California. If LinkedIn does 89 | not act to enforce a breach of this Agreement, that does not mean that 90 | LinkedIn has waived its right to enforce this Agreement. The Agreement does 91 | not create a partnership, agency relationship, or joint venture between the 92 | parties. Neither party has the power or authority to bind the other or to 93 | create any obligation or responsibility on behalf of the other. You may not, 94 | without LinkedIn’s prior written consent, assign or delegate any rights or 95 | obligations under these terms, including in connection with a change of 96 | control. Any purported assignment and delegation shall be ineffective. The 97 | Agreement shall bind and inure to the benefit of the parties, their respective 98 | successors and permitted assigns. If any provision of the Agreement is 99 | unenforceable, that provision will be modified to render it enforceable to the 100 | extent possible to give effect to the parties’ intentions and the remaining 101 | provisions will not be affected. This Agreement is the only agreement between 102 | you and LinkedIn regarding the Licensed Materials, and supersedes all prior 103 | agreements relating to the Licensed Materials. 104 | 105 | Last Updated: March 2019 106 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2021 LinkedIn Corporation 2 | All Rights Reserved. 3 | 4 | Licensed under the LinkedIn Learning Exercise File License (the "License"). 5 | See LICENSE in the project root for license information. 6 | 7 | Please note, this project may automatically load third party code from external 8 | repositories (for example, NPM modules, Composer packages, or other dependencies). 9 | If so, such third party code may be subject to other license terms than as set 10 | forth above. In addition, such third party code may also depend on and load 11 | multiple tiers of dependencies. Please review the applicable licenses of the 12 | additional dependencies. 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Learning Bash Scripting 2 | This is the repository for the LinkedIn Learning course Learning Bash Scripting. The full course is available from [LinkedIn Learning][lil-course-url]. 3 | 4 | Bash, or the Bourne Again Shell, is a widely popular command-line interpreter for administration and programming tasks. But Bash is different than most scripting languages. That's why Scott Simpson spends some time in this course running you through the syntax—introducing variables, numbers, and control structures—so you can start writing scripts right away. He shows you how to wrap up multiline operations in one file, implement flow control, and interact with users to get input. Plus, he offers challenges along the way that allow you to put what you've learned to the test. 5 | 6 | ## Learning Objectives 7 | - What is Bash? 8 | - Understanding Bash script syntax 9 | - Creating a basic Bash script 10 | - Displaying text with "echo" 11 | - Working with numbers, strings, and arrays 12 | - Reading and writing text files 13 | - Working with loops 14 | - Using functions 15 | - Getting user input during execution 16 | - Ensuring a response 17 | 18 | ## Instructions 19 | Please see the [Snippets.md](https://github.com/LinkedInLearning/bashscripting-2874016/blob/main/Snippets.md) file for all of the commands used in the course. 20 | 21 | ### Instructor 22 | 23 | **Scott Simpson** 24 | 25 | _Creating technology courses as an Author at LinkedIn_ 26 | 27 | Check out my other courses on [LinkedIn Learning](https://www.linkedin.com/learning/instructors/scott-simpson?u=104). 28 | 29 | [lil-course-url]: https://www.linkedin.com/learning/learning-bash-scripting-2 30 | 31 | 32 | -------------------------------------------------------------------------------- /Snippets.md: -------------------------------------------------------------------------------- 1 | # Code Snippets used in Learning Bash Scripting on LinkedIn Learning 2 | 3 | This document contains the commands used in the course. 4 | 5 | ## 01_05 Bash expansions and substitutions 6 | 7 | `echo ~` 8 | 9 | `echo ~-` 10 | 11 | ## 01_06 Brace expansion 12 | 13 | `echo {1..10}` 14 | 15 | `echo {10..1}` 16 | 17 | `echo {01..10}` 18 | 19 | `echo {01..100}` 20 | 21 | `{echo a..z}` 22 | 23 | `echo {Z..A}` 24 | 25 | `echo {1..30..3}` 26 | 27 | `echo {a..z..2}` 28 | 29 | `touch file_{01..12}{a..d}` 30 | 31 | `echo {cat,dog,fox}` 32 | 33 | `echo {cat,dog,fox}_{1..5}` 34 | 35 | ## 01_07 Parameter expansion 36 | 37 | `greeting="hello there!"` 38 | 39 | `echo $greeting` 40 | 41 | `echo ${greeting:6}` 42 | 43 | `echo ${greeting:6:3}` 44 | 45 | `echo ${greeting/there/everybody}` 46 | 47 | `echo ${greeting//e/_}` 48 | 49 | `echo ${greeting/e/_}` 50 | 51 | `echo $greeting:4:3` 52 | 53 | ## 01_08 Command substitution 54 | 55 | `uname -r` 56 | 57 | `echo "The kernel is $(uname -r)."` 58 | 59 | `echo "Result: $(python3 -c 'print("Hello from Python!")' | tr [a-z] [A-Z])"` 60 | 61 | ## 01_09 Arithmetic expansion 62 | 63 | `echo $(( 2 + 2 ))` 64 | 65 | `echo $(( 4 - 2 ))` 66 | 67 | `echo $(( 4 * 5 ))` 68 | 69 | `echo $(( 4 / 5 ))` 70 | 71 | ## 02_02 Understanding Bash script syntax 72 | 73 | `nano myscript` 74 | 75 | ```bash 76 | #!/usr/bin/env bash 77 | echo "hello" 78 | 79 | # This is a comment 80 | echo "there" 81 | ``` 82 | 83 | `chmod +x myscript` 84 | `./myscript` 85 | 86 | ## 02_03 Displaying text with 'echo' 87 | 88 | `echo hello world` 89 | 90 | `worldsize=big` 91 | 92 | `echo hello $worldsize world` 93 | 94 | `echo "The kernel is $(uname -r)"` 95 | 96 | `echo The kernel is $(uname -r)` 97 | 98 | `echo The (kernel) is $(uname -r)` 99 | 100 | `echo The \(kernel\) is $(uname -r)` 101 | 102 | `echo 'The kernel is $(uname -r)` 103 | 104 | `echo "The (kernel) is $(uname -r)"` 105 | 106 | `echo "The (kernel) is \$(uname -r)"` 107 | 108 | `echo` 109 | 110 | `echo; echo "More space!"; echo` 111 | 112 | `echo -n "No newline"` 113 | 114 | `echo -n "Part of "; echo -n "a statement"` 115 | 116 | ## 02_04 Working with variables 117 | 118 | ```bash 119 | #!/usr/bin/env bash 120 | 121 | mygreeting=hello 122 | mygreeting2="Good Morning" 123 | number=6 124 | 125 | echo $mygreeting 126 | echo $mygreeting2 127 | echo $number 128 | ``` 129 | 130 | ```bash 131 | #!/usr/bin/env bash 132 | 133 | myvar="Hello!" 134 | echo "The value of the myvar variable is: $myvar" 135 | myvar="Bonjour!" 136 | echo "The value of the myvar variable is: $myvar" 137 | 138 | declare -r myname="Scott" 139 | echo "The value of the myname variable is: $myname" 140 | myname="Michael" 141 | echo "The value of the myname variable is: $myname" 142 | 143 | declare -l lowerstring="This is some TEXT!" 144 | echo "The value of the lowerstring variable is: $lowerstring" 145 | lowerstring="Let's CHANGE the VALUE!" 146 | echo "The value of the lowerstring variable is: $lowerstring" 147 | 148 | declare -u upperstring="This is some TEXT!" 149 | echo "The value of the upperstring variable is: $upperstring" 150 | upperstring="Let's CHANGE the VALUE!" 151 | echo "The value of the upperstring variable is: $upperstring" 152 | ``` 153 | 154 | `declare -p` 155 | 156 | `env` 157 | 158 | `echo $USER` 159 | 160 | ## 02_05 Working with numbers 161 | 162 | `echo $((4+4))` 163 | 164 | `echo $((8-5))` 165 | 166 | `echo $((2*3))` 167 | 168 | `echo $((8/4))` 169 | 170 | `echo $(( (3+6) - 5 * (5-2) ))` 171 | 172 | `a=3` 173 | 174 | `((a+=3))` 175 | 176 | `echo $a` 177 | 178 | `((a++))` 179 | 180 | `echo $a` 181 | 182 | `((a++))` 183 | 184 | `echo $a` 185 | 186 | `((a--))` 187 | 188 | `echo $a` 189 | 190 | `(($a++))` 191 | 192 | `((a++))` 193 | 194 | `echo $a` 195 | 196 | `a=$a+2` 197 | 198 | `echo $a` 199 | 200 | `declare -i b=3` 201 | 202 | `b=$b+3` 203 | 204 | `echo $b` 205 | 206 | `echo $((1/3))` 207 | 208 | `declare -i c=1` 209 | 210 | `declare -i d=3` 211 | 212 | `e=$(echo "scale=3; $c/$d | bc)` 213 | 214 | `echo $e` 215 | 216 | `echo $RANDOM` 217 | 218 | `echo $(( 1 + $RANDOM % 10 ))` 219 | 220 | `echo $(( 1 + $RANDOM % 20 ))` 221 | 222 | ## 02_06 Comparing values with test 223 | 224 | `help test` 225 | 226 | `[ -d ~ ]` 227 | 228 | `echo $?` 229 | 230 | `[ -d /bin/bash ]; echo $?` 231 | 232 | `[ -d /bin ]; echo $?` 233 | 234 | `[ "cat" = "dog" ]; echo $?` 235 | 236 | `[ "cat" = "cat" ]; echo $?` 237 | 238 | `[ 4 -lt 5 ]; echo $?` 239 | 240 | `[ 4 -lt 3 ]; echo $?` 241 | 242 | `[ ! 4 -lt 3 ]; echo $?` 243 | 244 | ## 02_07 Comparing values with extended test 245 | 246 | `[[ 4 -lt 3 ]]; echo $?` 247 | 248 | `[[ -d ~ && -a /bin/bash ]]; echo $?` 249 | 250 | `[[ -d ~ && -a /bin/mash ]]; echo $?` 251 | 252 | `[[ -d ~ || -a /bin/bash ]]; echo $?` 253 | 254 | `[[ -d /bin/bash ]] && echo ~ is a directory` 255 | 256 | `ls && echo "listed the directory"` 257 | 258 | `true && echo "success!"` 259 | 260 | `false && echo "success!"` 261 | 262 | `[[ "cat" =~ c.* ]]; echo $?` 263 | 264 | `[[ "bat" =~ c.* ]]; echo $?` 265 | 266 | ## 02_08 Formatting and styling text output 267 | 268 | `echo -e "Name\t\tNumber"; echo -e "Scott\t\t123"` 269 | 270 | `echo -e "This text\nbreaks over\nthree lines"` 271 | 272 | `echo -e "\a"` 273 | 274 | `echo -e "Ding\a"` 275 | 276 | `echo -e "\033[33;44mColor Text\033[0m"` 277 | 278 | `echo -e "\033[91;100mColor Text\033[0m"` 279 | 280 | `echo -e "\033[91;100mColor Text"` 281 | 282 | `echo -e "\033[33;44mColor Text"` 283 | 284 | `echo -e "\033[4;31;40mERROR:\033[0m\033[31;40m Something went wrong.\033[0m"` 285 | 286 | ```bash 287 | #!/usr/bin/env bash 288 | 289 | ulinered="\033[4;31;40m" 290 | red="\033[31;40m" 291 | none="\033[0m" 292 | 293 | echo -e $ulinered"ERROR:"$none$red" Something went wrong."$none 294 | ``` 295 | 296 | ## 02_09 Formatting output with printf 297 | 298 | `echo "The results are: $(( 2 + 2 )) and $(( 3 / 1 ))"` 299 | 300 | `printf "The results are: %d and %d\n" $(( 2 + 2 )) $(( 3 / 1 ))` 301 | 302 | ```bash 303 | #!/usr/bin/env bash 304 | 305 | echo "----10----| --5--" 306 | 307 | echo "Right-aligned text and digits" 308 | printf "%10s: %5d\n" "A Label" 123 "B Label" 456 309 | 310 | echo "Left-aligned text, right-aligned digits" 311 | printf "%-10s: %5d\n" "A Label" 123 "B Label" 456 312 | 313 | echo "Left-aligned text and digits" 314 | printf "%-10s: %-5d\n" "A Label" 123 "B Label" 456 315 | 316 | echo "Left-aligned text, right-aligned and padded digits" 317 | printf "%-10s: %05d\n" "A Label" 123 "B Label" 456 318 | 319 | echo "----10----| --5--" 320 | ``` 321 | 322 | `printf "%(%Y-%m-%d %H:%M:%S)T\n" 1279994448` 323 | 324 | `date +%s` 325 | 326 | `date +%Y-%m-%d\ %H:%M:%S` 327 | 328 | `printf "%(%Y-%m-%d %H:%M:%S)T\n" $(date +%s)` 329 | 330 | `printf "%(%Y-%m-%d %H:%M:%S)T\n"` 331 | 332 | `printf "%(%Y-%m-%d %H:%M:%S)T is %s\n" -1 "the time"` 333 | 334 | ## 02_10 Working with arrays 335 | 336 | `declare -a snacks=("apple" "banana" "orange")` 337 | 338 | `echo ${snacks[2]}` 339 | 340 | `snacks[5]="grapes"` 341 | 342 | `snacks+=("mango")` 343 | 344 | `echo ${snacks[@]}` 345 | 346 | `for i in {0..6}; do echo "$i: ${snacks[$i]}"; done` 347 | 348 | `declare -A office` 349 | 350 | `office[city]="San Francisco"` 351 | 352 | `office["building name"]="HQ West"` 353 | 354 | `echo ${office["building name"]} is in ${office[city]}"` 355 | 356 | ## 03_01 Conditional statements with the 'if' keyword 357 | 358 | ```bash 359 | #!/usr/bin/env bash 360 | 361 | declare -i a=3 362 | 363 | if [[ $a -gt 4 ]]; then 364 | echo "$a is greater than 4!" 365 | else 366 | echo "$a is not greater than 4!" 367 | fi 368 | ``` 369 | 370 | ```bash 371 | #!/usr/bin/env bash 372 | 373 | declare -i a=3 374 | 375 | if [[ $a -gt 4 ]]; then 376 | echo "$a is greater than 4!" 377 | elif (( $a > 2 )); then 378 | echo "$a is greater than 2." 379 | else 380 | echo "$a is not greater than 4!" 381 | fi 382 | ``` 383 | 384 | ## 03_02Working with while and until loops 385 | 386 | ```bash 387 | #!/usr/bin/env bash 388 | 389 | echo "While Loop" 390 | 391 | declare -i n=0 392 | while (( n < 10 )) 393 | do 394 | echo "n:$n" 395 | (( n++ )) 396 | done 397 | 398 | echo -e "\nUntil Loop" 399 | declare -i m=0 400 | until (( m == 10 )); do 401 | echo "m:$m" 402 | (( m++ )) 403 | sleep 1 404 | done 405 | ``` 406 | 407 | ```bash 408 | #!/usr/bin/env bash 409 | 410 | echo "While Loop" 411 | 412 | declare -i n=0 413 | while (( n < 10 )) 414 | do 415 | echo "n:$n" 416 | (( n++ )) 417 | done 418 | 419 | echo -e "\nUntil Loop" 420 | declare -i m=0 421 | until ((m > m)); do 422 | echo "m:$m" 423 | (( m++ )) 424 | done 425 | ``` 426 | 427 | ## 03_03 Introducing 'for' loops 428 | 429 | ```bash 430 | #!/usr/bin/env bash 431 | 432 | for i in 1 2 3 433 | do 434 | echo $i 435 | done 436 | 437 | for i in 1 2 3; do echo $i; done 438 | ``` 439 | 440 | ```bash 441 | #!/usr/bin/env bash 442 | 443 | for i in {1..100} 444 | do 445 | echo $i 446 | done 447 | ``` 448 | 449 | ```bash 450 | #!/usr/bin/env bash 451 | 452 | for (( i=1; i<=100; i++ )) 453 | do 454 | echo $i 455 | done 456 | ``` 457 | 458 | ```bash 459 | #!/usr/bin/env bash 460 | 461 | declare -a fruits=("apple" "banana" "cherry") 462 | for i in ${fruits[@]} 463 | do 464 | echo "Today's fruit is: $i" 465 | done 466 | ``` 467 | 468 | ```bash 469 | #!/usr/bin/env bash 470 | 471 | for i in $(ls) 472 | do 473 | echo "Found a file: $i" 474 | done 475 | ``` 476 | 477 | ## 03_04 Selecting behavior using 'case' 478 | 479 | ```bash 480 | #!/usr/bin/env bash 481 | animal="dog" 482 | case $animal in 483 | cat) echo "Feline";; 484 | dog|puppy) echo "Canine";; 485 | *) echo "No match! 486 | esac 487 | ``` 488 | 489 | ## 03_05 Using functions 490 | 491 | ```bash 492 | #!/usr/bin/env bash 493 | 494 | greet() { 495 | echo "Hi there." 496 | } 497 | 498 | echo "And now, a greeting..." 499 | greet 500 | ``` 501 | 502 | ```bash 503 | #!/usr/bin/env bash 504 | 505 | greet() { 506 | echo "Hi there, $1" 507 | } 508 | 509 | echo "And now, a greeting..." 510 | greet Scott 511 | ``` 512 | 513 | ```bash 514 | #!/usr/bin/env bash 515 | 516 | greet() { 517 | echo "Hi there, $1. What a nice $2" 518 | } 519 | 520 | echo "And now, a greeting..." 521 | greet Scott Morning 522 | greet Everybody Evening 523 | ``` 524 | 525 | ```bash 526 | #!/usr/bin/env bash 527 | 528 | numberthing() { 529 | declare -i i=1 530 | for f in $@; do 531 | echo "$i: $f" 532 | (( i += 1 )) 533 | done 534 | echo "This counting was brought to you by $FUNCNAME." 535 | } 536 | 537 | numberthing $(ls /) 538 | echo 539 | numberthing pine birch maple spruce 540 | ``` 541 | 542 | ```bash 543 | #!/usr/bin/env bash 544 | 545 | var1="I'm variable 1" 546 | 547 | myfunction() { 548 | var2="I'm variable 2" 549 | local var3="I'm variable 3" 550 | } 551 | myfunction 552 | 553 | echo $var1 554 | echo $var2 555 | echo $var3 556 | ``` 557 | 558 | ## 03_06 Reading and writing text files 559 | 560 | ```bash 561 | #!/usr/bin/env bash 562 | 563 | for i in 1 2 3 4 5 564 | do 565 | echo "This is line $i" > ~/textfile.txt 566 | done 567 | ``` 568 | 569 | ```bash 570 | #!/usr/bin/env bash 571 | 572 | for i in 1 2 3 4 5 573 | do 574 | echo "This is line $i" >> ~/textfile.txt 575 | done 576 | ``` 577 | 578 | ```bash 579 | #!/usr/bin/env bash 580 | 581 | while read f 582 | do echo "I read a line an it says: $f" 583 | done < ~/textfile.txt 584 | ``` 585 | 586 | ## 04_01 Working with arguments 587 | 588 | ```bash 589 | #!/usr/bin/env bash 590 | 591 | echo "The $0 script got the argument $1" 592 | ``` 593 | 594 | ```bash 595 | #!/usr/bin/env bash 596 | 597 | echo "The $0 script got the argument $1" 598 | echo "Argument 2 is $2" 599 | ``` 600 | 601 | ```bash 602 | #!/usr/bin/env bash 603 | 604 | for i in $@ 605 | do 606 | echo $i 607 | done 608 | ``` 609 | 610 | ```bash 611 | #!/usr/bin/env bash 612 | 613 | for i in $@ 614 | do 615 | echo $i 616 | done 617 | 618 | echo "There were $# arguments." 619 | ``` 620 | 621 | ## 04_02 Working with options 622 | 623 | ```bash 624 | #!/usr/bin/env bash 625 | 626 | while getopts u:p: option; do 627 | case $option in 628 | u) user=$OPTARG;; 629 | p) pass=$OPTARG;; 630 | esac 631 | done 632 | 633 | echo "user: $user / pass: $pass" 634 | ``` 635 | 636 | ```bash 637 | #!/usr/bin/env bash 638 | 639 | while getopts u:p:ab option; do 640 | case $option in 641 | u) user=$OPTARG;; 642 | p) pass=$OPTARG;; 643 | a) echo "got the A flag";; 644 | b) echo "got the B flag";; 645 | esac 646 | done 647 | 648 | echo "user: $user / pass: $pass" 649 | ``` 650 | 651 | ```bash 652 | #!/usr/bin/env bash 653 | 654 | while getopts :u:p:ab option; do 655 | case $option in 656 | u) user=$OPTARG;; 657 | p) pass=$OPTARG;; 658 | a) echo "got the A flag";; 659 | b) echo "got the B flag";; 660 | ?) echo "I don't know what $OPTARG is!" 661 | esac 662 | done 663 | 664 | echo "user: $user / pass: $pass" 665 | ``` 666 | 667 | ## 04_03 Getting input during execution 668 | 669 | ```bash 670 | #!/usr/bin/env bash 671 | 672 | echo "What is your name?" 673 | read name 674 | echo "What is your password?" 675 | read -s pass 676 | read -p "What's your favorite animal? " animal 677 | 678 | echo "name: $name, pass: $pass, animal: $animal" 679 | ``` 680 | 681 | `help read` 682 | 683 | ```bash 684 | #!/usr/bin/env bash 685 | 686 | echo "Which animal" 687 | select animal in "cat" "dog" "bird" "fish" 688 | do 689 | echo "You selected $animal!" 690 | break 691 | done 692 | ``` 693 | 694 | ```bash 695 | #!/usr/bin/env bash 696 | 697 | echo "Which animal" 698 | select animal in "cat" "dog" "quit" 699 | do 700 | case $animal in 701 | cat) echo "Cats like to sleep.":; 702 | dog) echo "Dogs like to play catch.";; 703 | quit) break;; 704 | *) echo "I'm not sure what that is.";; 705 | done 706 | ``` 707 | 708 | ## 04_04 Ensuring a response 709 | 710 | ```bash 711 | #!/usr/bin/env bash 712 | 713 | read -ep "Favorite color? " -i "Blue" favcolor 714 | echo $favcolor 715 | ``` 716 | 717 | ```bash 718 | #!/usr/bin/env bash 719 | 720 | if (($#<3)); then 721 | echo "This command requires three arguments:" 722 | echo "username, userid, and favorite number." 723 | else 724 | # the program goes here 725 | echo "username: $1" 726 | echo "userid: $2" 727 | echo "favorite number: $3" 728 | fi 729 | ``` 730 | 731 | ```bash 732 | #!/usr/bin/env bash 733 | 734 | read -p "Favorite animal? " fav 735 | while [[ -z $fav ]] 736 | do 737 | read -p "I need an answer! " fav 738 | done 739 | 740 | echo "$fav was selected." 741 | ``` 742 | 743 | ```bash 744 | #!/usr/bin/env bash 745 | 746 | read -p "Favorite animal? [cat] " fav 747 | if [[ -z $fav ]]; then 748 | fav="cat" 749 | fi 750 | echo "$fav was selected" 751 | ``` 752 | 753 | ```bash 754 | #!/usr/bin/env bash 755 | 756 | read -p "What year? [nnnn] " year 757 | until [[ $year =~ [0-9]{4} ]]; do 758 | read -p "A year, please! [nnnn] " year 759 | done 760 | echo "Selected year: $year" 761 | ``` 762 | -------------------------------------------------------------------------------- /Solutions/fortune: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # A fortune-telling game 4 | 5 | echo -e "\t\t Welcome to the " 6 | echo -e "\t\t🔮 \033[5mMyStIcAl sPhErE\033[0m 🔮" 7 | echo 8 | 9 | waitingnumber=$(( 0 + $RANDOM % 3 )) 10 | mysterynumber=$(( 1 + $RANDOM % 10 )) 11 | 12 | declare -a fortunes=( 13 | "You are likely to achieve the outcome you seek." 14 | "Today is not a good day to do that." 15 | "While it might seem unlikely, your chances are good." 16 | "If you believe you will be successful, that's half the battle." 17 | "If you cared enough to ask, you care enough to make it happen." 18 | "I think you already know the answer to that." 19 | "Stop wondering and start doing!" 20 | "Yes, sure, whatever, I'm busy." 21 | "Next Thursday might be a better day to do that." 22 | "Sure, but what will the neighbors think?" 23 | ) 24 | 25 | case $waitingnumber in 26 | 0) sleep 1; echo "One moment please..."; sleep 1;; 27 | 1) sleep 1; echo "Your fortune will be along shortly..."; sleep 2;; 28 | 2) sleep 1; echo "Preparing your fate..."; sleep 1;; 29 | 3) sleep 1; echo "The veil of mystery is dark today..."; sleep 3;; 30 | esac 31 | 32 | echo 33 | echo ${fortunes[mysterynumber]} 34 | echo 35 | -------------------------------------------------------------------------------- /Solutions/multigame: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # A three-in-one game app 4 | 5 | # The game definitions 6 | guess() { 7 | local -i mynumber=$(( 1 + $RANDOM % 10 )) 8 | read -p "I'm thinking of a number between 1 and 10. What do you think it is? " theguess 9 | if (( theguess == mynumber )); then 10 | echo "You got it! Great Job!"; echo 11 | else 12 | echo "Nope. I was thinking of $mynumber. Try again!"; echo 13 | fi 14 | sleep 1 15 | choosegame 16 | } 17 | 18 | flip() { 19 | local -i mynumber=$(( 1 + $RANDOM % 2 )) 20 | if (( mynumber == 1 )); then 21 | local face="HEADS" 22 | else 23 | local face="TAILS" 24 | fi 25 | printf "I flipped a coin and it was: %s\n\n" $face 26 | sleep 1 27 | choosegame 28 | } 29 | 30 | dice() { 31 | local -i mynumber=$(( 1 + $RANDOM % 6 )) 32 | local -i mynumber2=$(( 1 + $RANDOM % 6 )) 33 | printf "I rolled two dice and the results are: %s and %s.\n\n" $mynumber $mynumber2 34 | sleep 1 35 | choosegame 36 | } 37 | 38 | # The game chooser 39 | choosegame() { 40 | select game in "Guessing Game" "Flip a Coin" "Dice Roll" "Exit" 41 | do 42 | case $game in 43 | "Guessing Game") guess;; 44 | "Flip a Coin") flip;; 45 | "Dice Roll") dice;; 46 | "Exit") exit;; 47 | *) echo "Please choose from the menu.";; 48 | esac 49 | done 50 | } 51 | 52 | # If there's an argument provided, jump right to that game. Otherwise, show the game chooser. 53 | case $1 in 54 | "guess") guess;; 55 | "flip") flip;; 56 | "dice") dice;; 57 | *) choosegame;; 58 | esac 59 | -------------------------------------------------------------------------------- /Solutions/sysreport: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # A script to output a brief summary of system information 4 | 5 | freespace=$(df -h / | awk 'NR==2 {print $4}') 6 | freemem=$(free -h | awk 'NR==2 {print $4}') 7 | 8 | greentext="\033[32m" 9 | bold="\033[1m" 10 | normal="\033[0m" 11 | 12 | printf -v logdate "%(%Y-%m-%d)T" 13 | 14 | echo -e $bold"Quick system report for "$greentext"$HOSTNAME"$normal 15 | printf "\tKernel Release:\t%s\n" $(uname -r) 16 | printf "\tBash Version:\t%s\n" $BASH_VERSION 17 | printf "\tFree Storage:\t%s\n" $freespace 18 | printf "\tFree Memory:\t%s\n" $freemem 19 | printf "\tFiles in pwd:\t%s\n" $(ls | wc -l) 20 | printf "\tGenerated on:\t%s\n" $logdate 21 | 22 | --------------------------------------------------------------------------------