14. Scripting and Automation

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Exit Codes

Every command terminates with an exit code. The $? special variable contains the exit code from the last executed command. In addition the exit command will both exit a script or routine and set an exit code. The following examples illustrate how the $? special variable and the exit command can be used in scripts.

Git Storage Locations

Git allows true multi-user, multi-project collaboration by allowing each user's workstation its own Git repository that works in conjunction with the remote repository. You can also work from multiple remote Git repositories for different projects or for different pieces of a project. The following table describes the four separate Git storage locations.

14.3.5 Bash Scripting Logic Facts

In addition to the basic commands, scripts can contain scripting logic constructs to control the flow of the script. This lesson covers the following topics: Branching constructs Looping constructs Exit codes

User Variables

In the bash shell, user variables are treated the same as environment variables and shell variables. Consider creating them with lowercase names to avoid environment and shell variables being overwritten with new values. > In most cases, create user variables at the same time as you assign them a value. - Enter the name of the variable, the equal sign (=), and then the value to assign the variable. > Reference the variable using the dollar sign ($). - When a dollar sign followed by a variable name is encountered in a bash command, the value of the variable is used instead of the variable name. - In bash, this is described as expanding the variable. > There are a few bash commands, like the read command, that will create a variable and assign a value to it. > A user variable can be created using the declare command. - The declare command can be used every time to create a variable. - The declare command is mostly used with shell arithmetic. > A variable can be deleted using the unset command.

Environment Variables, Shell Variables and Shell Environment Types

Linux is a multi-processing operating system, and each shell environment is spawned as a process. > As a process is created, environment information is gathered from a variety of files and settings on the system, and made available to the shell process. > This shell environment is implemented as key-value pairs or environment variables. > Each environment variable has a name that's assigned a value or multiple values. > Bash startup routines and bash shell startup scripts can add shell variables to the shell process. - The way that shell variables are added to a shell process depends on the shell environment type. > An interactive shell reads from standard-input (the keyboard) and writes to standard-output (the display screen). There are two kinds of interactive shells. - A login shell requires a user to provide a user ID and password. If you logged in using the Linux console or through a remote SSH session, it's a login shell. - A non-login shell does not require a user ID and password. The terminal windows in the Gnome desktop environment is an example of a non-login shell. - Bash shell startup scripts that add shell variables are only run in interactive shells. > A non-interactive shell does not interact with the user. Examples of a non-interactive shell are when a cron job starts or when a shell script is run. - Bash shell startup scripts do not run in non-interactive shells.

Shell Variables

Many people confuse shell variables with environment variables, since their names are in uppercase and they seem to be available in every shell session. > Shell variables aren't inherited like environment variables. > Most shell variables are created by shell startup scripts. One way to see the difference between environment variables and shell variables is to run two commands, printenv and set, and compare the results. > The printenv command lists only environment variables. > The set command lists all variables, including environment variables. > Any variable listed in the set command output that isn't in the printenv output is a shell variable. Another way to see the difference between environment variables and shell variables is to add the printenv and set commands to a script. > If printenv is run interactively, its results are identical to a script that runs the printenv command. > The set command run interactively will give different results than the set command run in a script. - This is due to the shell variables that are added by the shell startup files that are only run in interactive shell environments Shell variables are created just like environment variables by entering the variable's name followed by the equal sign and then the value to be assigned to the name.

git mv

Moves files, like the mv command, but the git mv command also notifies the index of the change.

Positional Parameters

Positional parameters are a series of special variables that contain the arguments given when the shell is invoked. The names of these special variables are digits, so they're referenced by $1, $2, $3, $4, and so on.

Which of the following describes the function of the export command? Makes the command history available to a child process. Makes a mount point available to a remote server. Spawns a new subshell for command execution. Sets environment variables.

Sets environment variables. The export command sets or converts a shell variable into an inheritable environment variable.

git config

Sets git configuration values in configuration files.

Given the following bash script: #!/bin/bash mynumber=5 guess=0 echo -e "I am thinking of a number from 1 to 10\n" read -p "Enter guess: " guess if (( guess == mynumber )) then echo "That is correct!" elif (( guess != mynumber )); then echo "Sorry, that is not my number!" fi Which of the following would be displayed if the number 12 is entered as the guess? 5 Sorry, that is not my number! error: number out of range That is correct!

Sorry, that is not my number! Entering the guess of 12 will result in the output, "Sorry, that is not my number!" The if statement will evaluate 12 and compare it to 5. Since it is not equal, the next elif statement checks to make sure the number does not equal 5 and displays the message. This bash script does not produce any of the other answers.

git add

Tells the index to add a file to the next commit for you. This is sometimes called staging the file.

Variable declarations

The declare -i command is used to type a variable as an integer. It can only contain whole numbers. It can't contain text or numbers with decimal places. The declare -f command is used to display all defined functions or just a specific defined function. e.g. (SEE PICTURE) The output of this script is the integer 12, because the shell treats the variable values as integers. *Numeric text strings can also be converted to integers using the following format: echo $[$num1+$num2] gives an output of 12 regardless of whether the declare command is used.

e.g.

The find command returns an exit code of 0 when a given filename is found. If it doesn't find the file, it returns with an exit code of 1. The exit code is captured in the result=$? command and used in the case structure.

Shell declaration

The first line in a script that holds the path to the bash interpreter.

Special Parameters

The following is a list of special parameters that can only be referenced using the dollar sign ($*, $#, $?, etc.) Their values are set and maintained by the bash shell.

for/do/done

The for/do/done construct implements a for loop. A for loop executes a set of commands a set number of times. A for loop: > Is useful when a specific action needs to be done a set number of times. > Executes all commands between the do and done statements. These are required. > Can be used with a list of items with one action being done for each item in the list. The seq command can be used to create a sequence of numbers for use in a for loop: > When using only one number in the command, seq starts at 1 and counts to the specified number. > When two numbers are given in the command, seq begins with the first number and counts up to the second number. > When three numbers are given in the command, seq starts at the first number and counts in increments of the second number up to the third number. e.g. The script uses a for loop to ask the correct number of multiplication questions. The loop starts at 0 and increments from 0 to 12. This ensures that the correct number of questions are asked. seq 10 counts from 1 to 10. seq 5 15 starts at 5 and counts to 15. seq 5 5 100 starts at 5 and counts to 100 in increments of 5. (for example 5, 10, 15, 20...) seq 10 -1 -10 starts at 10 and counts down to -10. *Other methods used to create a for loop include: > for looper in 1 2 3 4 5 counts from 1 to 5. > for looper in {1..5} counts from 1 to 5. > for looper in {0..10..2} counts from 0 to 10 in increments of 2.

Index

The index is part of the local repository. The index stores the list of files and tracks changes to the files.

Local Repository

The local Git repository is a copy of the remote repository that's stored on your computer. The local repository: > Stores all additions, changes, and deletions. > Allows you to push all your local changes to the remote repository at the appropriate time. > Allows you to make changes offline and apply changes when you're connected to the internet.

Branching

The logic in a bash script that performs different actions based on a specific condition or user input.

Looping

The logic in a bash script that repeatedly runs a set of commands according to a specific set of conditions.

time command

The output shows three values as follows: > real - The time from the moment the Enter key was pressed until the moment the command is completed. > user - The amount of CPU time spent in user mode. > system - The amount of CPU time spent in kernel mode. e.g. time wget wget https://wordpress.org/latest.zip use the wget command to download the zip file, but also displays the time it took: real 0m1.604s user 0m0.042s sys 0m0.099s

Remote repository

The remote Git repository is a copy of your project's files stored on a remote server. > This repository is important for projects that have multiple collaborators. > It gives you a central place to store your team members' work. > You can create a remote repository on your own Git server, or you can use one of the many Git repositories online.

e.g.

The results of the id -u command is zero (0) if the root account is being used. If root is not being used the script exits with a code of 101. The elif statement checks if a configuration file exits. If not, the script exits with a code of 102. Otherwise (else), normal processing commands are run and the script exits with a code of zero (0).

Shell declaration

The shell declaration should come first in the script. It starts with a number sign and exclamation point (#!), followed by the path to the shell executable. A common nickname for this line is shebang. e.g. #!/bin/bash specifies that the script will run in the bash shell.

Given the command ls > myfiles which of the following describes the results? The ls command lists only the files that match those stored in the myfiles file. The ls command outputs the contents of the myfiles file. The ls command takes the stdin from myfiles and displays the results. The stdout of the ls command is redirected to the myfiles file.

The stdout of the ls command is redirected to the myfiles file. The stdout of the ls command is redirected to the myfiles file.

The time Command

The time command is used to determine how long a given command takes to run. It is useful for testing the performance of your scripts and commands.

until/do/done

The until/do/done construct implements an until loop. An until loop is nearly identical to a while loop, but evaluates the condition using the opposite logic: > The e while loop executes commands while a condition is true. > The until loop executes commands until a condition is true.

while/do/done

The while/do/done construct implements a while loop. A while loop continuously executes all commands between the do and done statements while a specific condition evaluates to true. The while loop is useful for repeating an action until a specified condition is met. > A while loop requires do and done statements. > A while loop can create infinite loops if the condition never evaluates to false. e.g. (SEE PICTURE) This script uses a while loop to keep the user guessing numbers until they get the answer. As long as the number is not 23, the if statements keep giving the user clues as to whether the number is higher or lower. As soon as the user types 23, the while loop exits and the final statement displays telling the user that the guess is correct.

Basic Bash Script Rules and Components

There are basic rules that govern how a bash script should be written and run. > Specify the bash shell is used to run the script. > Use comments to explain what the script does. > Use exit 0 to end the script. > Assign execute permissions to the script with the chmod command. > Use one of the following methods to run the script: - Add the folder that contains the script to the PATH environment variable, then enter the script name at the shell prompt. - Save the script in a folder that is already in the PATH, such as /usr/bin or /bin, then enter the name of the script. - Type the full path name to the script to run the script from anywhere. - Type ./script_name to run the script if it resides in the current directory. (./ indicates the present working directory.) The following table lists some simple scripting components:

Shell Expansions

There are may types of shell expansions. Two important expansions are variable expansion and command expansion. Variable expansion is known as parameter expansion and uses the ${} construct. The following examples illustrate parameter expansion. Command expansion is also known as command substitution and uses the $() construct. Command substitution uses the output of a command to replace the command itself. The command within the parentheses is run, and the output is substituted. Often, command substitution is used as an argument for another command or to set a variable. The following examples illustrate command substitution.

Looping Constructs

There are three looping constructs that repeatedly run a set of commands according to a specified set of conditions.

Branching Constructs

There are two branching constructs that perform different actions based on specific conditions or user input.

Given the following bash script, what is the output if the user enters Kali? This is an unknown Linux distribution. CentOS and RHEL are RPM-based distributions. That is not a Linux distribution. Ubuntu is based on Debian.

This is an unknown Linux distribution. A case statement works well for testing two or more ways a condition could be evaluated. The case statement will check the input for a match. If no match is found, the catch all statement, represented by "*)", will be used. With user input of Kali, no match will be found, and the catch-all statement will be displayed.

Development Workspace

This is the folder on your computer where you do your work. > You can add new files to your project, modify files, and remove files. > After you make changes to your workspace, you can tell Git to update all the repositories to reflect your changes.

Setting up a Project

To begin working on a project, you will need to create a local repository. One way to do this is to use the git init command. Be aware: > The git init command is used only once for the initial setup. > You will typically run it in the folder where your existing project files are located. > It will create a new .git subdirectory in your current working directory and a new master branch for your project > git init can also be used to create a new remote repository While you can use git init to create a new repository, many projects will already have a remote Git repository that contains the project files. In this case, the command you will use is git clone. This command will make a copy of the project repository on your computer. Be aware that git clone will: > Create the local working directory > Add a .git sub-directory to create the local repository > Put a copy of all the project's files on your computer. *To ensure that you are working on the latest latest version of the files and to prevent conflicts with changes other team members make, frequently update your local repository from the remote repository. When you want to add a new feature or experiment with something new in your project, you can use git branch to create a new branch for that change. Working in the separate branch makes it harder for you to break the main project with an unstable change. You can later discard the branch, or you can use git merge to merge the changes you made in that branch back into the main project. You can work from multiple remote Git repositories for different projects or for different pieces of a project.

14.2.6 Shell Environments, Bash Variables and Parameters Facts

To write helpful bash shell scripts, you need a good understanding of the environment that the script runs in including environment variables, shell variables, bash shell parameters, user variables, and expansions, This lesson covers the following topics: Environment Variables, Shell Variables and Shell Environment Types The time command

git fetch

Updates just the local repository.

git pull

Updates the local repository and your development workspace.

case/esac

Use the case/esac construct to branch a script when the condition being evaluated has several possible outcomes. > The case construct can have an unlimited number of possible options. > When the script evaluates an option as being true, all remaining options are skipped. > Each option can execute several lines of commands. > Close each case with two semi-colons. > Case structures must be closed using esac (case spelled backwards.) e.g. (SEE PICTURE) The script asks the user about season preferences and has a response for each common answer. The last option is a catch-all for any answer other than those specified in the script.

if/then/else/fi

Use the if/then/elif/else/fi construct evaluate conditions and branch based on the results. > The if statement defines the condition to be evaluated. > The then statement specifies the commands to perform if the condition evaluates to true. > The elif statement is run if the condition in the if statement evaluates to false. It also supplies another condition and specifies the commands to perform in the elif condition evaluates to true. > The else statement specifies the commands to perform if the condition evaluates to false. > Operands include: = (equal to) != (not equal to) > (greater than) < (less than) > The if command requires spaces between the conditions and the operand. > The if command also requires spaces between the conditions and the brackets ('[' and ']'). > The construct must be closed with the fi command. The test command can be used within an if/then/else/fi construct to evaluate whether a condition evaluates to true or false. The test command options include: -d tests whether a directory exists. -e tests whether a file exists. -f tests whether a regular file exists. -G tests whether the specified file exists and is owned by a specific group. -h or -L tests whether the specified file exists and if it is a symbolic link. -O tests whether the specified file exists and if it is owned by a specific user. -r tests whether the specified file exists and if the read permission is granted. -w tests whether the specified file exists and if the write permission is granted. -x tests whether the specified file exists and if the execute permission is granted. > Operands for test include: = tests whether strings are equivalent. != tests whether strings are not equivalent. -o is used to specify that either of the options can be equivalent. -eq tests whether integers are equivalent. -ne tests whether integers are not equivalent. -gt tests whether the first integer is greater than the second. -lt tests whether the first integer is less than the second. e.g. (SEE PICTURE) The script takes the user input and evaluates it to determine whether the user types George. If the user types George, the script responds with That's my name, too. Otherwise, the script responds with the statement under the else command. *The if statement could also be written using the test command.For example, if test $NAME = "George" test -f ~/myfile.txt determines whether a file named myfile.txt exists in the user's home directory. test -d ~/binin determines whether a directory named bin exists in the user's home directory. test $name = "George Washington" determines whether the value of the $name variable is George Washington. test $name -o $name2 = "George Washington" determines whether the value of either the $name or the name2 variable is George Washington. test $num1 -le $num2 determines whether the value of the variable num1 is less than the value of the variable num2.

printenv

When a environment variable name is added as an argument, printenv displays the environment variable's value. When no arguements are added, printenv displays a list of environment variables and their values. e.g. printenv PATH This command displays the value of the PATH environment variable. printenv This command lists all environment variables and their values.

Commands

When a script runs, it executes commands as if they were entered at the command line. Commands can be typed on a single line or separated using a semi-colon (;). The echo command displays information on the screen. It can display a literal value or a variable. Keep the following in mind: > It is a good practice to always use quotes when you want a variable to represent a literal value. > Use a dollar sign ($) to display the value of a variable. > Use a backslash (\) to display special characters. The read command creates a variable and prompts the user to type in text. It assigns the value the user types to the variable. By default, the user input is treated as a text string. e.g. #!/bin/bash ls /home/user/Pictures exit 0 This script uses the ls command to list the contents of the /home/user/Pictures directory. echo "Hello, Mr. Smith." displays Hello, Mr. Smith. on the screen. echo \"Hello, Mr. Smith\" displays "Hello, Mr. Smith." on the screen. echo pwd displays pwd on the screen. echo $variable1 displays the value of variable1. echo \$variable1 displays the literal string $variable1. #!/bin/bash echo "What is your name?" read variable1 echo "Hello," $variable1"." exit 0 The script prints What is your name? on the screen, prompts the user for input, captures the user's input in a variable named variable1, then displays the contents of that variable on the screen.

Storing Arrays in Variables

You can assign a variable multiple values by declaring it as an array. There are two types of arrays, indexed and associative. The following examples illustrate the use of arrays.

Managing the Repository

You can use the following commands to manage a repository.

You are writing a bash script that lists the contents of a file. You would like to have any stderr messages sent to a file. Which of the following commands will write the error message to a file? cat projects 2>&1 projects.err cat projects > projects.err cat projects 1> projects.err cat projects 2> projects.err

cat projects 2> projects.err cat projects 2> projects.err redirects stderr to projects.err. cat projects > projects.err redirects the output of the command to projects.err. It does not redirect stderr to the file. cat projects 1> projects.err redirects the output to the file, not the stderr. cat projects 2>&1 projects.err redirects stderr to stdout and displays any error on stdout. The file will not contain error messages.

Troy, a system administrator, created a script to automate some daily administrative tasks. Which of the following commands would make Troy's script, /scripts/dailytasks, executable by everyone, but writable only by its owner? chmod u=rwx,go=rx /scripts/dailytasks chmod 577 /scripts/dailytasks chmod u=x,g=x /scripts/dailytasks chmod 775 /scripts/dailytasks

chmod u=rwx,go=rx /scripts/dailytasks chmod u=rwx,go=rx /scripts/dailytasks sets the permissions for the owner to be able to read, write, and execute the script. Both group and other are assigned read and execute permisssions. chmod 577 /scripts/dailytasks would not give owner write permissions, but would give group and other write permissions. chmod u=x,g=x /scripts/dailytasks would only give execute permissions to owner and group. chmod 775 /scripts/dailytasks would give write permissions to group.

Given the following bash script: #!/bin/bash declare -i count=5 until [ $count -lt 3 ] do echo count $count count=count-1 done Which of the following shows the output from this script? count 5 count 4 count 3 count 3 count 4 count 5 count 1 count 2 count 3 count 4 count 5 count 5 count 4

count 5 count 4 count 3 This script produces the following output: count 5 count 4 count 3 The until loop starts with the value of 5 as the count and continues to decrease the count by one until the number is less than 3. At that point, the until loop stops. The script does not produce the other outputs.

Which of the following are valid ways to assign a variable a value in a bash script? (Choose TWO.) declare -i num1=4 variable1=Hello num1==5 type string variable1=Hello num1 := 7;

declare -i num1=4 variable1=Hello variable1=Hello and declare -i num1=4 are both ways to assign a variable a value. Declare is used to type a variable as an integer (whole numbers only). Variables hold values that the script uses when running. These values can be either numbers or text.

While writing a shell script, you want to perform some arithmetic operations. Which of the following commands is used to create an integer variable? declare -i variablename variablename integer; set variablename variablename(integer)

declare -i variablename declare -i variablename will create a variable named variablename where the type is integer (whole numbers only).

A script named myscript contains the following command line: echo $1 $2 $3 The following command is typed in an interactive shell. myscript dog cat bird frog Which of the following will be displayed in the interactive shell? frog bird cat dog dog cat bird dog cat bird frog

dog cat bird The command line references three positional parameters, $1 $2 and $3. When the script is run it is given four arguments. The script only echoes the first three positional parameters and ignores the rest.

Anna, a technician, executed a command to display the contents of a file and received the output. [user@linux ~]$ cat myfile.txt at: myfile.txt: No such file or directory Which of the following commands would Anna enter to find out the exit code that was returned by this command? exit echo $1 env echo $?

echo $? echo $? displays the exit code from the previously executed command. In this case, a value of 1 would displayed because the command failed. A 0 indicates no errors. echo $1 does not display anything. exit causes the shell to exit. env displays the current environment variables.

Given the following bash script, #!/bin/bash for i in $(ls) do echo item: $i done Which of the following shows possible output if the script is executed from Bill's home directory? item: / item: /home item: /home/bill item: /home/bill/Documents item: .bash_history item: .bash_logout item: .bash_profile item: bashrc item: Desktop item: Documents item: Downloads item: /home/sally item: /home/bill item: /home/mario item: /home/lucinda

item: Desktop item: Documents item: Downloads The script will loop through the output of the ls command and display each item. In this case, the three folders Desktop, Documents, and Downloads were the only three items in Bill's home directory. The for loop iterated through the output. The hidden file .bash_history, .bash_logout, and .bash_profile would not be include in the ls listing. The /home/sally and other directories would not be included in the ls listing. The root directory / and other directories would not be included in the ls listing.

Which of the following statements is true about the command myscript < mydata.txt? The output of myscript is appended to mydata.txt. myscript outputs (stdout) data received from the mydata.txt input (stdin). The output of mydata.txt is stored in myscript, where it is processed. myscript receives input (stdin) from mydata.txt.

myscript receives input (stdin) from mydata.txt. myscript receives input (stdin) from mydata.txt.

Given the following command sequence: echo 'blue orange green brown' | while read a b c d; do echo output: $b $c $a $d; done Which of the following is the correct output? output: blue orange green brown output: b c a d output: b l u e output: orange green blue brown

output: orange green blue brown The results of the while loop will produce output: orange green blue brown. The while loop will read in the four values from the echo command and display them in a different order based on the variables $b $c $a $d. output: blue orange green brown is the incorrect result since the second echo displays the input in different order. output: b l u e is incorrect because the read command will read an entire word delimited by spaces into the variables. output: b c a d is incorrect because $b $c $a $d are variables and contain the values read from the first echo command.

You are working with a bash script, and there are multiple variables being used. Which of the following commands can be used to determine which commands are environment variables and which are shell variables? (Choose TWO). export set cat .bash_rc declare printenv

set printenv One way to see the difference between environment variables and shell variables is to run two commands, printenv and set, and compare the results. The printenv command lists only environment variables. The set command lists all variables, including environment variables.

From the bash command prompt, which of the following commands directly executes /usr/bin/scripts/cleanup.sh? exec cleanup.sh cleanup.sh source /usr/bin/scripts/cleanup.sh export /usr/bin/scripts/cleanup.sh

source /usr/bin/scripts/cleanup.sh source /usr/bin/scripts/cleanup.sh directly executes the script. export /usr/bin/scripts/cleanup.sh returns a "Not a valid identifier" error. cleanup.sh returns a "Command not found..." error. exec cleanup.sh returns a "Not found" error.

Which of the following commands deletes a variable? rm unset typeset -r declare -r

unset You can delete a variable using the unset command. rm is used for file and directory delete operations. declare -r and typeset -r are used to make a variable read-only.

When creating a bash script, it is important to document the purpose of the script. Which of the following is a valid comment? # Comment text // Comment text !! Comment text $ Comment text

# Comment text omments begin with a number sign (#). The shell ignores these lines when running the script. Comments help communicate how the script was constructed and what it is designed to do. // will return the error "Is a directory." $ and !! will both return the error "Command not found."

Which of the following shell declarations should be entered on the first line of a script for a system that uses the bash shell? /bin/tsh #!/bin/csh /bin/bash #!/bin/bash

#!/bin/bash #!/bin/bash is the shell declaration that is added to the first line of a bash script. #! is referred to as a shebang or hashbang and is followed by the path to the shell./bin/bash is the path to the shell and is not the correct syntax for a shell script./bin/tsh is the path the trusted shell, tsh.#!/bin/csh would be used if the C shell was being used instead of the bash shell.

Variables

> Variables hold values that the script uses when running. These values can be either numbers or text. Keep the following in mind when using variables: Linux script variables are commonly written using all capital letters. This helps programmers quickly identify them. > When creating variables, place the equals sign (=) immediately after the variable with no space. If a space follows the variable name, the script treats it as a command, and tries to execute it. > Use a space after the equals sign (=) only when you want the variable to be the output of a command. > Use quotes if a variable value has a space in it. It is a good practice to always use quotes when you want a variable to represent a character string. e.g. variable1=Hello assigns variable1 the value of Hello. variable1 = Hello causes an error because the script tries to run the command variable1, which by default does not exist. variable1="Hello, Mr. Smith" assigns variable1 the value of Hello, Mr. Smith. variable1=Hello, Mr. Smith assigns variable1 the value of Hello, then displays an error because it treats Mr. as a command and tries to execute it. variable1=pwd assigns variable1 the value of pwd. variable1= pwd assigns variable1 the value of the result of running the pwd command. For example, /home/jdoe. *You can manipulate environment variables from within a script. For example, you could modify the MAILTO environment variable by including MAILTO=root in a script. This will cause notifications or other conditional events to be mailed to the root superuser account by default.

Indexed array

A bash array that is indexed using a number.

Associative array

A bash array where the index is a character identifier instead of a number.

Command substitution

A bash construct in the form of $() or ` ` that substitutes the results of a command specified in the construct.

Variable expansion

A bash construct in the form of ${} that substitutes the variables value for the name of a variable.

Scripts and Environment Variable Inheritance

A bash shell runs in a Linux process. Each Linux process has a parent process. > To run a script from a parent bash shell: - A child process is created. - The child process opens a bash shell. - The script is run in the child bash shell. > The child shell inherits environment variables from its parent process. - A copy of the parent shell's environment variables is given to the child shell. - Any environment variable added to the parent shell after the child shell is created won't be available to the child shell. - The child shell can manipulate these environment variables without affecting the parent's environment variables.

Array variable

A bash variable that can hold multiple values that are referenced by the variable name and an index.

Environment variable

A bash variable that is inherited by child shells.

Shell variable

A bash variable usually added by a shell startup script.

Git

A distributed version-control system for tracking changes in source code during software development. GIT is most often used for coordinating work among programmers, but it can be used to track changes in any set of files.

Shell arithmetic

A feature of the bash shell that evaluates arithmetic expressions.

Repository

A file location where the files related to your project are stored. Every Git directory on every computer is a full-fledged repository with complete history and full version-tracking abilities, independent of network access or a central server.

Variable

A key-value pair that maps a variable name to a value.

Comment

A line in a bash shell script that helps a script writer understand how the script is constructed, but is ignored when the script is run.

Positional parameter

A series of special variables that contain the arguments given when the shell is invoked or when a script is run.

Special parameters

A set of special variables that are maintained by the shell and contain values such as the number of positional parameters, the status of the last executed command, etc.

Interactive shell

A shell that a user can interact with through stdin (the keyboard) and stdout (the display screen) that runs the bash startup scripts.

Non-interactive shell

A shell that does not interact with the user like the shell that runs a script.

Exit code

A value that is set when a bash command or script is executed.

Integer variable

A variable that can be assigned a value based on the results of a shell arithmetic equation.

Integer Variables and Shell Arithmetic

All bash variables are stored as character strings. The declare -i command will treat the variable as an integer. > An integer is a whole number, like the numbers you use to count. - An integer can be positive, negative, or zero. > The declare -i command allows the variable to be assigned a value using shell arithmetic. > Shell arithmetic uses: - The plus character (+) for addition - The minus or dash character (-) for subtraction - The asterisk character (*) for multiplication - The slash character (/) for division. > Other operators are described on the bash man page. > To use shell arithmetic: - Enter the variable and the equal sign (=), and then enter an arithmetic equation. - Equations can be made up of variables and operators with no spaces between them - Parenthesis can be used to specify the order that the arithmetic operations are performed. - Don't use the dollar sign to use the value for a variable. The following examples illustrate the use of shell arithmetic.

Non-login shell

An interactive shell that doesn't require the user to enter a user ID and password.

Login shell

An interactive shell that requires the user to enter a user ID and password.

14.3 Bash Scripting Logic

As you study this section, answer the following questions: What constructs are used for branching in a bash script? What is the difference between the if/then/elif/fi construct and the case/esac construct? What constructs are used for looping in a bash script? What is the difference between the while, until, and for constructs? How are exit codes used? In this lesson, you will learn to: Employ branching constructs in a bash script. Employ looping constructs in a bash script. Employ exit codes in a bash script. Key terms for this section include the following:

14.1 Bash Shell Scripting

As you study this section, answer the following questions: What is the purpose of the shell declaration (the shebang)? How can you comment out lines in a shell script? Which methods can you use to run a script from the command line? Why might you need to use the declare command in a script? In this lesson, you will learn to: Create a simple bash script. Execute and source a script. Use variables within a script. Key terms for this section include the following:

14.2 Shell Environments, Bash Variables and Parameters

As you study this section, answer the following questions: What is the purpose of the shell declaration (the shebang)? How can you comment out lines in a shell script? Which methods can you use to run a script from the command line? Why might you need to use the declare command in a script? In this lesson, you will learn to: Use variables and parameters in a bash script. Use shell arithmetic in a bash script. Use arrays, variable expansions, and command substitution in a bash script. Key terms for this section include the following:

14.4 Version Control Using Git

As you study this section, answer the following questions: Why would you want to used Git? What is a Git repository? What types of Git repositories exist? What are their functions? Key terms for this section include the following:

14.1.4 Scripting Facts

At its most basic level, a bash script is a set of commands stored in a file. When the bash shell reads the file, it executes the commands as if they were typed at the keyboard. This lesson covers the following topics: Basic bash script rules and components The time command

14.1.5 Practice Questions

CIST 2431

14.2.7 Practice Questions

CIST 2431

14.3.6 Practice Questions

CIST 2431

Comments

Comments begin with a number sign (#). The shell ignores these lines when running the script. Comments help communicate how the script was constructed and what it is designed to do.

Shell Expansions

Continued

export variable name

Converts a shell variable into an inheritable environment variable. e.g. export training This command converts the training variable into an environment variable.

git cp

Copies files or directories like the cp command. Like git mv, it also notifies the index of the change.

git rm

Creates a file or directory delete request in the index. The requested file or directory will be removed from your filesystem and the local Git repository at the next commit.

variable name=value

Creates a shell variable with the given name and value e.g. training=TestOut This command creates the shell variable with the name of "training" that has the value "TestOut".

delare -x variable name=value

Creates and exports an environment variable at the same time. e.g. declare -x training=TestOut This command creates an environment variable named "training" that has the value "TestOut".

14.4.4 Version Control Using Git Facts

Effective and efficient collaboration on projects, large or small, requires a great deal of coordination and version management. Git is a version control system that tracks changes to files and helps keep all user files up to date. It helps avoid problems like saving over one another's important work and collisions from two people editing a file at once. This lesson covers the following topics: Git storage locations Setting up a project Managing the repository Commit and push

Environment Variables

Environment variables are mostly used by the shell. The following commands are used when working with environment variables.


Kaugnay na mga set ng pag-aaral

Ch. 30: Care of Chest Tubes (Nurs 309)

View Set

Module 26 Classical Conditioning

View Set

Animal Handling/Restraint - Cattle, goat, and sheep

View Set

chapter 14 mutation and DNA repair

View Set

simple machines, Work 6.1, 6.2 & 6.3

View Set