bash

¡Supera tus tareas y exámenes ahora con Quizwiz!

How do you pass an argument with spaces in it to a function?

# I still don't know. Supposedly adding quotes within the function will do: function makeRooibos { ingredients="$1" } makeRooibos rooibos # ...but that didn't work for me.

Write a bash script that prints out the contents of a file that is either passed in as a command line arg, or else read from STDIN. Write the commands to execute the script using 1) cmd line input, 2) STDIN.

# ifElseExample.sh if [ $# -eq 1 ] # REMEMBER THAT [$# -eq 1] (no spaces) IS DIFFERENT THAN [ $# -eq 1 ] (spaces) !! then nl $1 else nl /dev/stdin fi To execute: $ ifElseExample.sh FILE or $ cat dude | ./ifElseExample

What is the first line of a bash script? What does it do? Does it have to be the first line?

#!/bin/bash #! = the shebang. /bin/bash = the path to the interpreter. Bash scripts use the bash interpreter, but for other types of scripts the interpreter will be different. The shebang MUST be the first line, and there may be no spaces before the #.

What is the difference between 'let' and 'expr' ? Write an expression using 'expr' that finds the remainder of 11 when divided by 2 (modulus) and assigns that value to a variable, a.

'let' assigns the value to a variable. 'expr' prints the output to the screen. 'expr' can however be used to assign a value to a variable, like this: a=$( expr 11 % 2)

What do each of these options do for the command 'read'? -a -d -e -n -p -s -t

-a aname The words are assigned to sequential indices of the array variable aname, starting at 0. All elements are removed from aname before the assignment. Other name arguments are ignored. -d delim The first character of delim is used to terminate the input line, rather than newline. -e If the standard input is coming from a terminal, Readline is used to obtain the line. -n nchars read returns after reading nchars characters rather than waiting for a complete line of input. -p prompt Display prompt, without a trailing newline, before attempting to read any input. The prompt is displayed only if input is coming from a terminal. -r If this option is given, backslash does not act as an escape character. The backslash is considered to be part of the line. In particular, a backslash-newline pair may not be used as a line continuation. -s Silent mode. If input is coming from a terminal, characters are not echoed. -t timeout Cause read to time out and return failure if a complete line of input is not read within timeout seconds. This option has no effect if read is not reading input from the terminal or a pipe.

false; echo $? what does this print?

1 (0=true ; 1=false). why? it's just the convention. It can be useful - it's very easy to check for success, and know when to investigate if there's an error.

Write expressions for the following using let, expr, and (( )) 1) increment a by 1 2) set a = a + 3

1) let a++ 1) can't do it. no += cmd for expr, and $( expr a=a+1) = 12+3, not 15 1) (( a++ )) 2) let a+=3 2) # no += cmd for expr 2) (( a+=3 ))

Check for these 2 things first when a bash.

1) spaces. 2) indentations.

Write commands to do the following: 1) change the timestamp of a file 2) create 100 files named file1, file2, etc.

1) touch -d 'Apr 22 15:10' 2) touch file{1,2,3...} or for i in $(seq 1 100); do echo -n "file${i} "; touch file${i} 2>&1; done

1. $0 2. $1 - $9 3. $# 4. $@ 5. $? 6. $$ 7. $USER 8. $HOSTNAME 9. $SECONDS 10. $RANDOM 11. $LINENO 12. $(!!)

1. The name of the Bash script 2. The first 9 arguments/parameters to the bash script. 3. How many arguments were passed to the Bash script. 4. All the arguments supplied to the Bash script. 5. The exit status of the most recently run process. 6. The process ID of the current script. 7. The username of the user running the script. 8. The hostname of the machine the script is running on. 9. The number of seconds since the script was started. 10. Returns a different random number each time is it referred to. 11. Returns the current line number in the Bash script. 12. Returns the last output (e.g. locate *models/simworld; cd $(!!) )

Why are these 3 files special? What do each do? STDIN, STDOUT, STDERR cat rockstars.txt tyler alloy axlrose gunsnroses Write a command that pipes the contents of a text file 'rockstars.txt' to a program called 'rocktime'. Write a command within rocktime that sorts the input.

Each process has 3 special files that can be used to combine single purpose commands, e.g. pipe STDIN of one command to the next one. Not all processes require an input (e.g. ls, dir), or outputs (e.g. mv). STDIN: the input to a given process/program. STDOUT: the output of a given process/program. STDERR: outputs error messages of a given process/program. cat rockstars.txt | ./rocktime # rocktime cat /dev/stdin | cut -d' ' -f 2 | sort -- cat rockstars.txt lists the contents of rockstars.txt; this list is the input to the program rocktime. -- cat /dev/stdin lists the input. cut -d' ' divides the list by spaces, -f 2 specifies the 2nd field, which is then sorted

A short history of bash: what was its initial purpose? how has it expanded?

It was initially developed as a tool for interacting with the system, and has expanded to include more powerful scripting capabilities. Many decisions regarding its behavior were made considering only the needs of the user; scripting capabilities had to be worked in later, around those decisions (e.g. this is why user variables impact the outcome of a bash script). Bash scripts are still a powerful tool for quickly and easily joining existing programs.

Does bash care about indenting?

No, but people do, so do it for readability.

In script1, var1=rock. If script1 calls script2, what does var1 equal in script2?

Nothing; var1 is not defined in script2. The scope of the variable is limited to the process in which it is executed, and because there are separate processes for script1 and script2, var1 is only defined in script1.

What bash function do square brackets [ ] reference? What are the operators that code for the following? 1) The EXPRESSION is false. 2) The length of STRING is greater than zero. 3) The length of STRING is zero (ie it is empty). 4) STRING1 is equal to STRING2 5) STRING1 is not equal to STRING2 6) INTEGER1 is numerically equal to INTEGER2 (how is this different than #4?) 7) INTEGER1 is numerically greater than INTEGER2 8) INTEGER1 is numerically less than INTEGER2 9) FILE exists and is a directory. 10) FILE exists. 11) FILE exists and the read permission is granted. 12) FILE exists and it's size is greater than zero (ie. it is not empty). 13) FILE exists and the write permission is granted. 14) FILE exists and the execute permission is granted.

Square brackets [] reference the test command. e.g. test 001=1 ; echo $? returns true 1) ! EXPRESSION 2) -n STRING 3) -z STRING 4) STRING1 = STRING2 5) STRING1 != STRING2 6) INTEGER1 -eq INTEGER2 (= is a string comparison / char for char the same, whereas -eq does a numerical comparison / [001 -eq 1] returns true) 7) INTEGER1 -gt INTEGER2 8) INTEGER1 -lt INTEGER2 9) -d FILE 10) -e FILE 11) -r FILE 12) -s FILE 13) -w FILE 14) -x FILE

In a bash script, are variables global (visible everywhere in the script) or local (visible only within a function) by default? dan='software eng' Write a function called if_in_32 where dan='hardware eng' only inside the function.

Variables are global by default. dan='software eng' function if_in_32 { local dan='hardware eng' }

How does bash know how to execute a command typed into the terminal window? Where does it look to find the variable?

When a command is entered into a terminal, bash looks in a series of directories stored in a variable called $PATH. Path only looks in these directories, and it executes the first instance of the program or script that it finds.

How to execute a script from within a script

bash

Write a for loop that --

dollars = 1 while [ $dollars -le 10] OR until [ $dollars -ge 10] do echo 'earn a dollar' (( $dollars++ )) done

How do you find the length of var1='rockstar', or var2=3.14 ?

echo ${#var1}

var1='rockstar' What are the outputs of these cmds? echo 'you are a $var1' echo "you are a $var1"

echo 'you are a $var1' : you are a $var1 : you are a rockstar

Enter < ? > to see a list of all existing variables that bash knows.

env

export a variable 'rockstar'

export rockstar

Replace every instance of dog with Max in every file in /tmp unless the file already includes Max. Write a script that stops searching once it finds a file with Max in it. What happens if this script lives in /tmp?

for file in $( ls /tmp) if grep -Fxq 'Max' $file then continue fi do perl -p -i -e 's/dog/Max/g' $file done Using break instead of continue will stop the search once Max is found. If this script lives in /tmp, then it will replace dog with Max in itself, and then execute 's/Max/Max/g' for every other file, doing nothing for all subsequent files.

Are these equivalent expressions? What does a equal in either case? let "a=4+$1" let "a = $1+4" let a=$1+4 let a = $1+4

let "a=4+$1" results in an error - variables must come before values. let "a = $1+4" and let a=$1+4 are the same, and in both cases a = 4 + the first cmd line arg. let a = $1+4 results in an error. If there are no quotes, there must also be no spaces.

pipe the output of ls to less

ls | less

explain each part of ps aux | grep -i FILE

ps: report a snapshot of the process. a: select all processes except 1) both session leaders (getsid(0) returns the session ID of the calling process. getsid(p) returns the session ID of the process with process ID p. The session ID of a process is the process group ID of the session leader.) and 2) all processes not associated with a terminal. u: select by effective user ID. This selects the processes whose effective user name or ID is in userlist. The effective user ID describes the user whose file access permissions are used by the process (see geteuid(2)). Identical to U and --user. x: Lift the BSD-style "must have a tty" restriction, which is imposed upon the set of all processes when some BSD-style (without "-") options are used or when the ps personality setting is BSD-like. The set of processes selected in this manner is in addition to the set of processes selected by other means. An alternate description is that this option causes ps to list all processes owned bpassed following the y you (same EUID as ps), or to list all processes when used together with the a option. | : pipe. standard output of first command is directed as the input to the second command. grep : print lines matching a pattern - i : ignore case FILE : grep searches through files listed.

Write a command that asks a user for his name and accepts his input.

read -p 'username: ' uservar

Write a function called awesomize that adds awesomesauce to a sandwich if there is no awesomesauce (where 0 = no sauce and 1 = sauce). Use both acceptable formats for a function. Call the function. Set the output of the awesomize function equal to the variable 'sauced' without using command substitution inside of the awesomize function. How do you pass an arg to a function? How do you NOT pass an arg to a function?

sandwich=$1 function awesomize { if [ $sandwich -eq 0 ] then (( sandwich++ )) # Note! $sandwich doesn't work here. } OR awesomize () { (( sandwich++ )) } sauced=$(( awesomize $sandwich )) # calling the function from inside the script. - Do not put args in the (); parentheses are just there for decoration. - args are referenced as $1, $2, etc. within the function, e.g. awesomize this_sandwich -- NOT like this: awesomize (this_sandwich) -- also, NOT this: awesomize()

[ ] [[ ]] { }

test / [ ] : this is a built in function [[ ]] : enables additional functionality, e.g. usage of && and || instead of -a and -o (??) {} braces are used for parameter expansion, which is a mechanism for generating arbitrary strings, e.g. truncating, substituting, or using a default value for a variable.

Write a case statement that prints different statements depending on the day of the week.

today=`date +%A` case $today in Monday) echo hello monday ;; Wednesday) echo hello wednesday ;; esac

What is the output of this cmd? What is the cause of the error? var1 = rockstar

var1: command not found The error is caused by spaces on either side of the = sign.

assign the output of ls to a variable

var1=$(ls)

If read is expecting 3 inputs: read var1 var2 var3 and the user inputs 4 items: nirvana GunsNroses Metallica Queen then what do var1,2,3 equal?

var1=nirvana var2=GunsNroses var3=Metallica Queen


Conjuntos de estudio relacionados

Adding and Subtracting Rational Expressions Assignment

View Set

Fundamentals of Nursing: Chapter 2 Theory, Research, and Evidence-Based Practice

View Set

Honors Precalc (Caron) Final Notes (6.5, 9.1, 9.2)

View Set

SPC1017: FUNDAMENTALS OF SPEECH Chapter 5&6

View Set