lecture 6 bash scripting i: - script introduction; - variables & operations - conditions cse4251...
TRANSCRIPT
Lecture 6
Bash scripting I:- script introduction;- variables & operations- conditions
CSE4251 The Unix Programming Environment
1
shell script
• a series of shell commands placed in an ASCII text file
• Commands include– Anything you can type on the command line– Variables and Expressions– Control statements (if, while, for, ...)– Functions
“Hello World” in bash
• open/create a file: $ vim hello1.sh
#!/bin/bash# This is a comment!# This is another comment! echo Hello, World! #a comment after the cmd
tell OS the script is to be interpreted by /bin/bash, (i.e., this is a bash script instead of csh, ksh, ...)
the command executed in this script
“#!” or “shebang” tells OS this is a shell script
“Hello World” in bash
• open/create a file: $ vim hello1.sh
• add execution permission: $ chmod 744 ./hello1.sh• run the script: $ ./hello1.sh
#!/bin/bash# This is a comment!# This is another comment! echo Hello, World! #a comment after the cmd
[15:03:45][zhengm@apollo-tesla:~]$ ./hello1.shHello, World![15:03:52][zhengm@apollo-tesla:~]$
“Hello World” in bash
• How about this: $ vim hello2.sh
(run hello2.sh to see if the output matches your guess; we will cover the syntax in the following lectures)
#!/bin/bashecho "Hello World" echo "Hello World"echo "Hello * World"echo Hello * Worldecho Hello Worldecho "Hello" Worldecho Hello " " Worldecho "Hello \"*\" World"echo `hello` worldecho 'hello' world
Variables
• Set and use variables
• Set a variable based on user input:
#!/bin/bashMY_MSG="Hello World"echo $MY_MSG
#!/bin/bashecho What is your name?read USER_NAMEecho "Hello $USER_NAME "
Variables• Create a file based on user input
#!/bin/bashecho What is your name?read USER_NAMEecho "Hello $USER_NAME “echo "I will create a file called $USER_NAME_file for you" touch ${USER_NAME}_file
#!/bin/bashecho What is your name?read USER_NAMEecho "Hello $USER_NAME “echo "I will create a file called $USER_NAME_file for you"touch $USER_NAME_file
Wrong:
Correct:
Variables
• No space permitted on either side of = sign when initializing variables– What happens if there is a space?
# "VARIABLE =value" # ^ #Script tries to run "VARIABLE" command with one argument, "=value".
# "VARIABLE= value" # ^ #Script tries to run "value" command with #the environmental variable "VARIABLE" set to "".
• Unlike C, you can use a variable anywhere w/o declaration; it just means nothing/empty before setting– E.g. myvar1.sh
#!/bin/bashecho "MY_VAR is: $MY_VAR"MY_VAR="hi there"echo "MY_VAR is: $MY_VAR"
$ ./myvar1.shMY_VAR is:MY_VAR is: hi there
Scope of variables
• you can set a variable via command line, but you must “export” it so that it’s visible to later scripts
[16:10:51][zhengm@apollo-tesla:~/cse4251]$ MY_VAR=hi[16:18:38][zhengm@apollo-tesla:~/cse4251]$ ./myvar1.shMY_VAR is:MY_VAR is: hi there[16:18:40][zhengm@apollo-tesla:~/cse4251]$ export MY_VAR[16:19:22][zhengm@apollo-tesla:~/cse4251]$ ./myvar1.shMY_VAR is: hiMY_VAR is: hi there
Scope of variables
set in cmd line
invisible to the script
export
inherited value shows up
#!/bin/bashecho "MY_VAR is: $MY_VAR"MY_VAR="hi there"echo "MY_VAR is: $MY_VAR"
[16:10:51][zhengm@apollo-tesla:~/cse4251]$ MY_VAR=hi[16:18:38][zhengm@apollo-tesla:~/cse4251]$ ./myvar1.shMY_VAR is:MY_VAR is: hi there[16:18:40][zhengm@apollo-tesla:~/cse4251]$ export MY_VAR[16:19:22][zhengm@apollo-tesla:~/cse4251]$ ./myvar1.shMY_VAR is: hiMY_VAR is: hi there
Scope of variables
Note:the 2nd line is “hi there”, which implies that the inherited “hi” is overwritten by the “hi there” defined in the script!
• you can set a variable via command line, but you must “export” it so that it’s visible to later scripts
• By default, the value defined in the script has no effect outside of the script (disappears after the script finishes)
[16:19:22][zhengm@apollo-tesla:~/cse4251]$ ./myvar1.shMY_VAR is: hiMY_VAR is: hi there[16:19:24][zhengm@apollo-tesla:~/cse4251]$ echo $MY_VARhi
Scope of variables
“hi there” is gone;“hi” is the value before running the script
“hi there” defined in the script exists only when executing the script
• To make a value defined in the script visible/usable outside of the script, source (. ) the script
[16:34:39][zhengm@apollo-tesla:~/cse4251]$ . ./myvar1.shMY_VAR is: hiMY_VAR is: hi there[16:36:58][zhengm@apollo-tesla:~/cse4251]$ echo $MY_VARhi there
Scope of variables
“hi there” still there
source (.) the script
• double quotes (""): most characters (e.g., space, tab, *, etc) are not interpreted (i.e., they are taken literally) inside double quotes
Escape characters
#!/bin/bashecho 1 Hello Worldecho 2 "Hello World"
1 Hello World2 Hello World
#!/bin/bashecho 3 Hello * Worldecho 4 "Hello * World"
3 Hello escape.sh gamefile hello1.sh hello2.sh myvar1.sh World4 Hello * World
• What if want to output Hello “World”: use \
• How about this
Escape characters
#!/bin/bashecho 6 "Hello "World" "
#!/bin/bashecho 5 "Hello \"World \" "
5 Hello "World"
• ", $, `, and \ are still interpreted by the shell as special characters, even when they're in double quotes
Escape characters
#!/bin/bash
X=10echo "A quote is \", backslash is \\, backtick is \`."echo "A few spaces are ; dollar is \$. \$X is $X."
A quote is ", backslash is \ , backtick is `.A few spaces are ; dollar is $. $X is 10.
• bash variables are untyped – just character strings in essence– depending on context, bash permits arithmetic operations and
comparisons on variables– the determining factor is whether the value of a variable
contains only digits (i.e., 0-9)– bash does not support floating point by itself, but can use other
commands to handle floating point arithmetic (e.g., bc)
Type of variables
• Arithmetic operators: +, -, *, /, %, ++, --• Arithmetic relational operators:
-lt (<), -gt (>), -le (<=), -ge (>=), -eq (==), -ne (!=)• String comparison operators:
s1 = s2, s1 != s2, s1 < s2, s1 > s2, #can also use letters #like –lt, -gt, -ne
-n s1 #s1 is not null (contains one or more char.)-z s1 #s1 is null
• Logic operators (!, &&, ||)
Operators
• Basic arithmetic operators: +, -, *, /, %
Use let to do arithmetic operations
#!/bin/bashlet a=11 # Same as 'a=11' let a=a+5 # Equivalent to let "a = a + 5"
# (Double quotes and spaces make it more readable)echo "11 + 5 = $a" # 16 let "a /= 4" # Equivalent to let "a = a / 4" echo "128 / 4 = $a" # 32 let "a -= 5" # Equivalent to let "a = a - 5" echo "32 - 5 = $a" # 27 let "a *= 10" # Equivalent to let "a = a * 10" echo "27 * 10 = $a" # 270 let "a %= 8“ # Equivalent to let "a = a % 8" echo "270 modulo 8 = $a (270 / 8 = 33, remainder $a)" # 6
• Self-increment/decrement: ++, --
Use let to do arithmetic operations
#!/bin/bash# "let" permits C-style operators
a=6let a++ # C-style (post) incrementecho "6++ = $a" # 6++ = 7 let a-- # C-style decrementecho "7-- = $a" # 7-- = 6
# note: ++a, etc., also allowed
• If no let ...
Use let to do arithmetic operations
#!/bin/bash
a=2334let "a += 1"echo "a = $a”
a+=1echo "a = $a“
$ ./arithmetic.sha = 2335a = 23351
• the (( ... )) construct also permits arithmetic expansion and evaluation
Alternative to let: ((...))
#!/bin/basha=$(( 5 + 3 )) # Set a to 5 + 3, or 8(( a = 23 )) # Set a to 23
#+ with spaces on both sides of the "=". echo "a (initial value) = $a" # 23 (( a++ )) # Post-increment 'a', C-style. echo "a (after a++) = $a" # 24 (( a-- )) # Post-decrement 'a', C-style. echo "a (after a--) = $a" # 23 (( ++a )) # Pre-increment 'a', C-style.echo "a (after ++a) = $a" # 24 (( --a )) # Pre-decrement 'a', C-style. echo "a (after --a) = $a" # 23
• Let you decide whether to perform an action or not – the decision is taken by evaluating an expression
Conditions
#!/bin/bashif [[ "foo“ = "foo“ ]]; then
echo expression evaluated as true fi
• if ... then ...
• if ... then ... else ...#!/bin/bashif [[ "foo“ = "foo" ]]; then
echo expression evaluated as trueelse
echo expression evaluated as falsefi
Conditions• Conditions w/ variables
#!/bin/bashV1=“foo”V2=“bar”if [[ “$V1“ = “$V2" ]]; then #”” is optional, but better use it to
#avoid parsing error in case of #empty variables
echo expression evaluated as trueelse
echo expression evaluated as falsefi
Conditions
#!/bin/bash
V3="3"if [[ “$V3” = 1 ]]; then echo "expression evaluated as 1"elif [[ “$V3” = 2 ]]; then echo "expression evaluated as 2"else echo "expression evaluated as > 2"fi
• if ... then ... elif ...
• Complex condition
• Sometimes you may see single brackets [...] for conditions– alternative to double brackets [[ ... ]] but with more quirks– older but maybe more portable
Conditions
#!/bin/bash#...
if [[ “$varA” = 1 && (“$varB” = "t1" || “$varC” = "t2") ]]; thenecho blahblahblah
fi
Lab 2• http://web.cse.ohio-state.edu/~
zhengm/teaching/cse4251sp15/CSE4251%20Lab%202.htm
• DUE: 11:59pm, Tuesday, Mar 03, 2015
27