Module 6: Bash Scripting

Spread the love

INTRODUCTION – Bash Scripting

Welcome to this module which introduces you to the basics of Linux/Unix operating system capabilities among which are some aspects of Bash scripting scripting beginner-level programs with basic Linux commands all the way through process management, pivoting on the concept of redirection. Learn by example by scripting in Bash using variables and globs, to reach a point deeper within the more advanced concepts in Bash. In the end, we look at detailed comparisons of situations favorable for Bash over using Python.

Learning Objectives

  • Use basic Linux commands to work with files and directories.
  • Creating and executing Bash scripts.
  • Generation of output, with variables and globs, reflects modifications therein via scripts.
  • Working of loops in Bash scripts while it suits much more advanced uses of that scripting language.
  • Those prefer Bash to Python when compiling complex functions.

PRACTICE QUIZ: INTERACTING WITH THE COMMAND LINE

1. Which of the following commands will redirect errors in a script to a file?

  • user@ubuntu:~$ ./calculator.py < error_file.txt
  • user@ubuntu:~$ ./calculator.py 2> error_file.txt (CORRECT)
  • user@ubuntu:~$ ./calculator.py > error_file.txt
  • user@ubuntu:~$ ./calculator.py >> error_file.txt

You nailed it! The “2>” sign will redirect errors to a file.

2. When running a kill command in a terminal, what type of signal is being sent to the process?

  • SIGTERM (CORRECT)
  • SIGSTOP
  • SIGINT
  • PID

You got it! The kill Command sends a sign to terminate a specific pid.

3. What is required in order to read from standard input using Python?

  • echo file.txt
  • cat file.txt
  • The file descriptor of the STDIN stream
  • Stdin file object from sys module (CORRECT)

This command gathers user input in a continuous loop without breaking; we stop once the input ends by any means (like typing Ctrl+D or through the end of file). Very handy when you’re working with piped input or input redirection from files.

4. _____ are tokens delivered to running processes to indicate a desired action.

  • Signals (CORRECT)
  • Methods
  • Functions
  • Commands

Nice job! Yes, that is correct! It gives users an opportunity to freeze the execution of a script immediately. Signals provide a way of interacting with a process that is running, like pause or terminate it, or showing it how to respond to specified events. This can be particularly helpful when needing to manage processes in a more deliberate fashion or in the event that the user would want to gracefully handle interruptions (i.e., when the user hits Ctrl+C).

5. In Linux, what command is used to display the contents of a directory?

  • rmdir
  • cp
  • pwd
  • ls (CORRECT)

Nice job! The ls command lists the file contents of a directory.

6. Which of the following Linux commands will create an empty file?

  • touch (CORRECT)
  • pwd
  • mkdir
  • cd

Right on! The touch command will create an empty file.

7. How do you append the output of a command to a .txt file?

  • user@ubuntu:~$ ./calculator.py > result.txt
  • user@ubuntu:~$ ./calculator.py >> result.txt (CORRECT)
  • user@ubuntu:~$ ./calculator.py < result.txt
  • user@ubuntu:~$ print("This will append") 

It posts a single call of command output to an appeneded file.

8. Which of the following is the correct way of using pipes?

  • user@ubuntu:~$ cat sample.txt ./process.py
  • user@ubuntu:~$ cat sample.txt || ./process.py
  • user@ubuntu:~$ tr ' ' '\n' | sort | cat sample.txt
  • user@ubuntu:~$ cat sample.txt | tr ' ' '\n' | sort (CORRECT)

The material contained in the file is transmitted on separate lines and alphabetically arranged.

9. What can you type in the terminal to stop the traceroute command from running cleanly?

  • Ctrl-C
  • SIGINT (CORRECT)
  • Ctrl-Z
  • SIGSTOP

Right on! This sends a SIGINT signal to the program to stop processing cleanly.

PRACTICE QUIZ: BASH SCRIPTING

1. Which of the following commands will output a list of all files in the current directory?

  • echo * (CORRECT)
  • echo a*
  • echo *.py
  • echo ?.py

Right on! The star [*] globe will echo or output all files in the current directory.

2. Which module can you load in a Python script to take advantage of star [*] like in BASH?

  • ps
  • stdin
  • Glob (CORRECT)
  • Free

Yes! You need to import the glob module in order to do things you can do in BASH with a “*.”: use a “*” wildcard.

3. Conditional execution is based on the _____ of commands.

  • environment variables
  • parameters
  • exit status (CORRECT)
  • test results

In terms of Bash scripting, the condition basically depends on the result of exit status in the respective commands.

4. What command evaluates the conditions received on exit to verify that there is an exit status of 0 when the conditions are true, and 1 when they are false?

  • test (CORRECT)
  • grep
  • echo
  • export

Great! The command test checks specified conditions and exits with 0 for true and 1 for false.

5. The opening square bracket ([), when combined with the closing square bracket (]), is an alias for which command?

  • glob
  • test (CORRECT)
  • export
  • if

Right on! The test command can be called with square brackets ([]).

6. Which command will correctly run a bash script?

  • user@ubuntu:~$ #!/bin/bash
  • user@ubuntu:~$ ./bash.py 
  • user@ubuntu:~$ ./bash_sample.sh (CORRECT)
  • user@ubuntu:~$ ./sh.bash

Right on! A bash script is run with the .sh file extension.

7. When defining a variable you receive the “command not found” message. Which of the following commands will resolve this error?

  • User1= billy
  • $User2 =billy
  • User3 = $billy
  • User4=billy (CORRECT)

Great work! The variable “User4” has a value of “billy”.

8. A conditional block in Bash that starts with ‘if’, ends with which of the following lines?

  • fi (CORRECT)
  • if
  • else
  • grep

Right on! The if conditional ends with fi (a backwards “if”).

PRACTICE QUIZ: ADVANCED BASH CONCEPTS

1. Which command does the while loop initiate a task(s) after?

  • while
  • n=1
  • done
  • do (CORRECT)

Awesome! Tasks to be performed are written after do.

2. Which line is correctly written to start a FOR loop with a sample.txt file?

  • for file in sample.txt; do (CORRECT)
  • for sample.txt do in file
  • do sample.txt for file
  • for sample.txt in file; do

You nailed it! The file contents of the sample.txt document are loaded inside the file variable that will be able to perform the desired processes to process in the system.

3. Which of the following Bash lines contains the condition of taking an action when n is less than or equal to 9?

  • while [ $n -le 9 ]; do (CORRECT)
  • while [ $n -lt 9 ]; do
  • while [ $n -ge 9 ]; do
  • while [ $n -ot 9 ]; do

Right on!. This code will take action if the value of n is less than or equal to 9.

4. Which of the following statements are true regarding Bash and Python? [Check all that apply]

  • Complex scripts are better suited to Python. (CORRECT)
  • Bash scripts work on all platforms.
  • Python can more easily operate on strings, lists, and dictionaries. (CORRECT)
  • If a script requires testing, Python is preferable. (CORRECT)

Great show! As soon as scripts become quite complex, it is good to write the script in a much more general scripting language as Python.

Brilliant! Bash scripts are not harmful in terms of flexibility and power compared to getting an entire Python language in return, with its hundreds of different functions for string, list, and dictionary operations.

Exactly! Testing Python is much easier and needed verification means it needs to be simple.

5. The _____ command lets us take only bits of each line using a field delimiter.

  • cut (CORRECT)
  • echo
  • mv
  • sleep

Excellent!  The cut command lets us take only bits of each line using a field delimiter.

6. Which “for” conditional line will add users Paul and Jeremy to a user variable?

  • for users in Paul Jeremy
  • for user in Paul Jeremy (CORRECT)
  • for Paul Jeremy in user
  • for Paul & Jeremy in user

Nice job! The elements in the variable user are Paul and Jeremy.

7. When using the following command, what would each line of the output start with?

user@ubuntu:~$ tail /var/log/syslog | cut -d' ' -f3-

  • CRON[257236]:
  • October
  • 31
  • 10:18:41 (CORRECT)

Woohoo! When you choose the cut command, picking option -f3 will allow you to monitor logs’s time.

8. Which of the following statements would make it better to start using Python instead of Bash?

  • Operate with system commands.
  • Use on multi-platforms. (CORRECT)
  • Operate with system files.
  • Run a single process on multiple files.

Right on! Theeasy way is to stick within one programming langauge and its most important modules, which in Python-based multi-platform work would be Python and its batteries-included library.

EDIT FILES USING SUBSTRINGS

1. In Linux, what does the cat command allow you to do?

  • Extract a given number of characters or columns from a file. 
  • Process text line-by-line and print any lines that match a specified pattern.
  • Create single or multiple files, view the contents of a file, concatenate files, and redirect output in the terminal or other files. (CORRECT)
  • Search text and match a string or pattern within a file.

Correct

2. What is a delimiter? 

  • A target file
  • A text string containing characters 
  • A character or set of characters that separate text strings (CORRECT)
  • A file location

Correct

3. A single greater than sign (>) or a double greater than sign (>>) can be used to redirect standard output. What do commands with a single greater than sign (>) do with existing file content? 

  • Delete the file content 
  • Overwrite the file content (CORRECT)
  • Append the file content
  • Duplicate the file content

Correct

4. A peer asks which Linux command she should use to process text line-by-line and print the lines that match a specified pattern, such as a file directory. What do you tell her?

  • The cat command
  • The grep command (CORRECT)
  • The cut command
  • The overwrite command

Correct

5. What is the difference between a command that ends with -f 1-3 and a command that ends with -f 1,3?

  • The first specifies fields 1 and 3 and the second specifies fields 1 through 3.
  • There is no difference.
  • The first specifies fields 1 through 3 and the second specifies fields 1 and 3. (CORRECT)
  • The first is a cut command and the second is a cat command.

Correct

6. On Unix-like operating systems, the command test is a command-line utility that evaluates conditional expressions. In the following command, what does the flag “-e” after “test” do? 

if test -e ~/data/jane_profile_07272018.doc; then echo "File exists"; else echo "File doesn't exist"; fi

  • This flag checks if the file jane_profile_07272018.doc is present in the file system. (CORRECT)
  • This flag deletes files including “jane”, “profile”, and “07272018” in the file system. 
  • This flag checks if the profile “jane” is present in the file 07272018.doc. 
  • This flag returns a list of all files including “jane”, “profile”, or “07272018” in the file system. 

Correct

7. After you created the text file oldFIels.txt and stored the “jane” lines there, what command let you view the contents of the newly generated file?

  • > oldFiles.txt
  • cat oldFiles.txt (CORRECT)
  • nano oldFiles.txt
  • chmod oldFiles.txt

Correct

8. Bash script allows three different iterative statements:, or “loops”. What is a “while” loop?

  • The execution of a group of statements over a control condition.
  • The execution of a set of instructions as long as the control condition remains false.
  • The execution of a set of instructions as long as the control condition remains true. (CORRECT)
  • The execution of a set of instructions as long as the control condition is specified.

Correct

9. A junior programmer has asked your advice on which Linux command to use to create single or multiple files, view the contents of a file, concatenate files, and redirect output in terminal or other files. Which Linux command would you tell them to use?

  • The cut command
  • The overwrite command
  • The cat command (CORRECT)
  • The grep command

Correct

10. What is the Linux command you should use to extract certain specific information columns from a larger database? 

  • The cut command (CORRECT)
  • The cp command
  • The grep command
  • The cat command

Correct

11. What will executing the command grep ‘jane’ ../data/list.txt do?

  • Return all lines containing the text string “jane” in the file list.txt. (CORRECT)
  • B: Create a target file named jane.list.txt.
  • Delete all lines containing the text string “jane” in the file list.txt.
  • Cut all lines containing the text string “jane” in the file list.txt.

Correct

12. What will the command cd data do? 

  • Navigate to the data directory. (CORRECT)
  • Duplicate the data directory. 
  • List the contents of the data directory. 
  • Copy the data directory.

Correct

13. Looking at the following command, how might you predict the fields in the file list.txt are delineated? 

grep " jane " ../data/list.txt | cut -d '...' -f 1

  • There is nothing to delineate the fields.
  • By an ellipsis (…)(CORRECT)
  • By a forward slash (/)
  • By a hyphen (-)

Correct

14. In Bash scripting, there are three primary iterative statements, commonly referred to as loops. Among these is the “until” loop. What is the purpose of the “until” loop?

  • The execution of a set of instructions as long as the control condition is specified.
  • The execution of a set of instructions as long as the control condition remains false. (CORRECT)
  • The execution of a set of instructions as long as the control condition remains true.
  • The execution of a group of statements over a set of items. 

Correct

15. When using the cut command, when is the -d option needed?

  • When fields are separated by delimiters (CORRECT)
  • When there are text strings 
  • When there is a set of fields 
  • When there is a range of fields

Correct

16. Which command should you use to check if a particular file is present in the file system?

  • The cut command
  • The overwrite command
  • The cat command
  • The test command (CORRECT)

Correct

17. While preparing to catch all “jane” lines and store them in a text file called oldFiles.txt, you had to create that file. Which of the following commands did you use to create oldFiles.txt? 

  • > oldFiles.txt (CORRECT)
  • # oldFiles.txt
  • cd ~/oldFiles.txt
  • >> oldFiles.txt

Correct

18. Bash script allows three different iterative statements:, or “loops”. What is a “for” loop?

  • The execution of a group of statements over a set of items. (CORRECT)
  • The execution of a set of instructions as long as the control condition remains false.
  • The execution of a set of instructions as long as the control condition remains true.
  • The execution of a set of instructions as long as the control condition is specified.

Correct

19. A software developer has been asked to extract the name, phone number, and address columns from a file that contains over 2,000 lines of customer data. Which of the following Linux commands should the developer use?

  • The cp command
  • The cut command (CORRECT)
  • The grep command
  • The cat command

Correct

20. A single greater than sign (>) or a double greater than sign (>>) can be used to redirect standard output. What do commands with a double greater than sign (>>) do with existing file content? 

  • Append the file content (CORRECT)
  • Overwrite the file content 
  • Duplicate the file content 
  • Delete the file content

Correct

21. The redirection commands cat > [file] and cat >> [file] are used to redirect standard output to a target file. What happens if that target file doesn’t exist?

  • The redirection command will be terminated. 
  • A new file with the same name will be created. (CORRECT)
  • Append file content in the existing file.
  • An input/output error will be returned.

Correct

22. Complete this sentence. The Linux command you should use to create single or multiple files, view the contents of a file, concatenate files, and redirect output in the terminal or other files is the ____command. 

  • cat (CORRECT)
  • grep 
  • overwrite 
  • cut

Correct

23. The grep command is an acronym: What does grep stand for? 

  • global regular expression process
  • global regular expression print (CORRECT)
  • global regular extraction process 
  • global regular expression pattern

Correct

24. What will executing the command cat list.txt do?

  • Amend the fields in the file list.txt.
  • Show the contents of the file list.txt. (CORRECT)
  • Duplicate the file list.txt.
  • Concatenate the fields in the file list.txt.

Correct

CONCLUSION – Bash Scripting

That being said, this module is about the in-depth examination of Linux operating system from the basic level through advanced scripting using Bash. So basically, this module goes over basic Linux commands and killer Linux processes with redirections as main focus.

As you proceed further, you will be preparing example Bash scripts that incorporate variables and globs as two most essential elements. The lesson particularly addresses advanced matters, exploring functions in the Bash language, which hopefully will give you an insight as to when it is better to use Bash for personal scripting needs than Python.

Leave a Comment