1. echo and if else fi commands
#! / bin / bash
echo hello; echo there
filename = demo.sh
if [-e "$ filename"]; then
echo "$ filename already exists!"; cp $ filename $ filename.bak
else
echo "$ filename does not exist!";
fi;
echo "File test complete!"
Running result (demo.sh does not exist):
hello
there
demo.sh does not exist!
File test complete!
It should be noted that filename = demo.sh cannot have spaces on both sides of the equal sign; if [-e "$ filename"], there are spaces on both sides of [].
2. Basic operation of shell 2.1 Variable is greater than, equal to, less than
#! / bin / bash
a = 1
if [$ a -gt 0]; then
echo "greater than zero!"
else
echo "no more than zero!"
fi
if [[$ a -lt 0]]; then
echo "less than zero!"
else
echo "no less than zero!"
fi
if [[a -eq 1]]; then
echo "equal to 1!"
else
echo "not equal to 1!"
fi
-gt means greater than; -lt means less than; -eq means equal. The running result is:
greater than zero!
no less than zero!
equal to 1!
2.2 Trinocular operator (? :)
#? is 3 operator
b = 10
((t = b <20? 6: 4)) # t = 6
echo "t = $ t"
# variable in () is a part region variable
(b = 20; echo "b = $ b") # b = 20
echo "b = $ b" # b = 10
Similar to languages such as C and java,? In the shell is also a trinocular operator. () Indicates that a local scope is established, which can temporarily block global variables. The running result of the above formula is:
t = 6
b = 20
b = 10
2.3 Array 2.3.1 Array creation
# () create an array
arr = (1 2 3 5 6)
echo "arr [3] = $ {arr [3]}"
Output:
arr [3] = 5
2.3.2 Array length
# get the length of array
echo "length of arr is $ {# arr [*]}" # 5
echo "length of arr is $ {# arr [@]}" # 5
Output:
length of arr is 5
length of arr is 5
2.3.3 Output array elements
# get all content of array
echo "arr: $ {arr [*]}" # 1 2 3 5 6
# or
echo "arr: $ {arr [@]}" # 1 2 3 5 6
Output:
arr: 1 2 3 5 6
arr: 1 2 3 5 6
2.3.4 Modify array elements
# assign a new element to an array
arr [1] = 100
echo "arr: $ {arr [@]}" # 1 100 3 5 6
# if assign index if out of bound, then auto create a new element of array
arr [10] = 20 # 1 100 3 5 6 20
echo "arr: $ {arr [@]}"
Output:
arr: 1 100 3 5 6
arr: 1 100 3 5 6 20
Note that if the assignment index exceeds the length of the array, it is equivalent to adding a new element to the end of the array.
2.3.5 Delete array elements
# delete the element of array
unset arr [1] # delete the arr [1], 1 3 5 6 20
echo "arr: $ {arr [*]}" # 1 3 5 6 20
# clear the whole array
unset arr
echo "$ {# arr [@]}" # length 0
Output:
arr: 1 3 5 6 20
0
unset If you keep up with the index of the array, delete the array element at that position; if you follow the array name directly, it is equivalent to emptying the array.
1 2 4
2
arr1: 2 4
2.3.7 Array element replacement
# replace
# $ {array_name [@] / origin_element / new_element}
# this operation does n‘t change the origin array
# and will return a string that seperated by space
echo "$ {arr1 [*] / 2/20}" # 20 4, arr1: 2 4
arr1 = ($ {arr1 [*] / 4/40}) # arr1: 2 40
echo "$ {arr1 [*]}" # 2 40
Output:
20 4
2 40
2.4 File operations
# file operation
if [! -w ‘t.txt’]; then
touch t.txt
fi
echo ‘test text‘> t.txt
cp t. {txt, back} # cp t.txt to t.back
filename = "/ home / lyrichu / login"
if [-r $ filename] # if file is readable
then
echo "$ filename is readable!"
else
echo "$ filename is not readable!"
fi
if [-e $ filename]
then
echo "$ filename exists!"
else
echo "$ filename does n’t exist!"
fi
Output:
/ home / lyrichu / login is not readable!
/ home / lyrichu / login does n’t exist!
The above code first checks whether the t.txt file is writable, if it is not writable, then recreate a file; then write the string ‘test text’ to the t.txt file; then copy the t.txt file to the t.back file;
Then determine whether the / home / lyrichu / login file is readable and exists.
2.5 {} Create a code block
# {} create a code block
a = 10; echo "a = $ a"
{a = 20;} # a = 20
echo "a = $ a" # a = 20
Output:
a = 10
a = 20
2.6 expr evaluates the value of an expression
val = `expr $ a + $ b` # a = 20, b = 10
echo "a + b = $ val" # a + b = 30
val = `expr $ a \ * $ b` # \ * means multiply, a * b = 10 * 20 = 200
echo "a * b = $ val"
# divide
val = `expr $ a / $ b` # 20/10 = 2
echo "a / b = $ val"
a + b = 30
a * b = 200
a / b = 2
20% 9 = 2
expr can calculate the value of the shell expression. The above formula calculates the +, *, /,% operations separately. Note that multiplication needs to use \ * escape.
2.7 Logical operators
if [$ a == $ b]
then echo "a == b!"
fi
if [$ a! = $ b]
then
echo "a! = b"
fi
# && logit and
if [[$ a -gt 10 && $ b -lt 20]]
then
echo "$ a> 10 and $ b <20!"
else
echo "bad condition!"
fi
# || logit or
if [[$ a -gt 15 || $ b -gt 15]]
then
echo "a> 15 or b> 15"
else
echo "a <= 15 and b <= 15"
fi
Output:
a! = b
20> 10 and 10 <20!
a> 15 or b> 15
== Used to compare numbers equal;! = Used to compare numbers unequal. && means logical AND in the shell; || means logical OR in the shell.
2.8 String operations
#! / bin / bash
s1 = "abhsgd"
# Get string length
echo "length of s1:" $ {# s1}
#Extract substring
# $ {string: position}, in the string, extract the substring starting from the position
echo $ {s1: 2} # hsgd
# $ {string: position: length}, string, extract the substring of length from the position
echo $ {s1: 2: 2} # hs
# $ {string # substring}, from the beginning of the string, delete the shortest substring matching substring, return the string after deleting the substring
echo $ {s1 # ab} #hsgd
# $ {string ## substring}, delete the longest matching substring from the beginning of string
echo $ {s1 ## abh} # sgd
# $ {string% substring}, delete the shortest substring matching substring from the end of string
echo $ {s1% gd} # absh
# $ {string %% substring}, delete the longest matching substring from the end of string
echo $ {s1 %% hsgd} # ab
# $ {string / substring / replacement}, use replacement to replace the first matching substring
echo $ {s1 / hs / HS} # abHSgd
# $ {string // substring / replacement}, use replacement to replace all matching substrings
s2 = ahjhjhhshdg
echo $ {s2 // h / H} # aHjHjHHsHdg
# $ {string / # substring / replacement}, if the prefix of string matches substring, then use replacement to replace the matched substring
echo $ {s2 / # ahj / AHJ} # AHJhjhhshdg
# $ {string /% substring / replacement}, if the suffix of string matches substring, then replacement is used to replace the matched substrin
g
echo $ {s2 /% shdg / SHDG} # ahjhjhhSHDG
## Note: The above replacement can be a regular expression, such as:
s3 = / home / lyrichu / demo.txt
# Get the file name
echo $ {s3 ## * /} # demo.txt
# Get the directory name
echo $ {s3% / *} # / home / lyrichu
Output:
length of s1: 6
hsgd
hs
hsgd
sgd
abhs
ab
abHSgd
aHjHjHHsHdg
AHJhjhhshdg
ahjhjhhSHDG
demo.txt
/ home / lyrichu
2.9 Control flow 2.9.1 if statement
a = 10
b = 20
if [$ a == $ b]
then
echo "$ a == $ b!"
elif [[$ a -gt $ b]]; then
echo "$ a> $ b!"
elif [[$ a -lt $ b]]; then
echo "$ a <$ b!"
else
echo "Error!"
fi
# test command
if test $ a -lt $ b
then
echo "$ a <$ b!"
else
echo "$ a> = $ b!"
fi
Output:
10 <20!
10 <20!
The test command is used to judge the truth of a statement.
2.9.2 for statement
# for loop
for i in 1 2 3 4
do
echo "The value is $ i"
done
# for loop of string
for s in This is a string
do
echo "$ s"
done
Output:
The value is 1
The value is 2
The value is 3
The value is 4
This
is
a
string
2.9.3 while loop
#while loop
i = 1
while (($ i <5))
do
echo "$ i"
let "i ++"
done
echo "Press CTRL + D to exit!"
echo -n "Who is the most beautiful girl?"
while read MAN
do
echo "Yes! $ MAN is really beautiful!"
done
Output:
1
2
3
4
Press CTRL + D to exit!
Who is the most beautiful girl? Yp
Yes! Yp is really beautiful!
2.9.4 case statement
# case mode
echo "Please input a number between 1 to 4!"
read input
case input in
1) echo "Your choice is 1!"
;;
2) echo "Your choice is 2!"
;;
3) echo "Your choice is 3!"
;;
4) echo "Your choice is 4!"
;;
*) echo "You do n‘t choose a number between 1 and 4!"
;;
esac
## break
while:
do
echo "PLease input a number between 1 and 5!"
read n
case $ n in
1 | 2 | 3 | 4 | 5) echo "Your input number is $ n!"
;;
*) echo "Your input is not between 1 and 5!"
break
;;
esac
done
Output:
Please input a number between 1 to 4!
3
Your choice is 3!
PLease input a number between 1 and 5!
5
Your input number is 5!
PLease input a number between 1 and 5!
10
Your input is not between 1 and 5!
2.10 Functions 2.10.1 A simple function with no parameters and no return value
func1 () {# fuction that does not have parameters
echo "This is my first function!"
}
# call function
func1
Output:
This is my first function!
2.10.2 Functions with return values
func2 () {# function with return
echo "This is function that has return!"
return 1
}
# use $? to get the function return value
func2
echo "The return value of func2 is $?"
Output:
This is function that has return!
The return value of func2 is 1
Use the return keyword at the end to return a value, use $? To get the return value of the function.
The function passes parameters, gets the total number of parameters, the parameter value, and the i-th parameter
# input parameters of function
# $ 1, $ 2, ... to the first n parameter
func3 () {
n = $ # # get the total number of parameters
echo "There are total $ n parameters of func3!"
echo "The first parameter is: $ 1"
echo "The second parameter is $ 2"
echo "The tenth parameter is $ {10}"
echo "The all parameters as string is: $ *"
}
func3 1 2 3 4 5 6 7 8 9 10 11 12
Output:
There are total 12 parameters of func3!
The first parameter is: 1
The second parameter is 2
The tenth parameter is 10
The all parameters as string is: 1 2 3 4 5 6 7 8 9 10 11 12
3. Some simple shell examples 3.1 Calculate the maximum of 3 numbers
# calculate the max value of 8,4,5
a = 5
b = 4
c = 8
i = $ a
if [[$ i -lt $ b]]
then
i = $ b
fi
if [[$ i -lt $ c]]
then
i = $ c
fi
echo "The max value of $ a, $ b, $ c is $ i"
Output:
The max value of 5,4,8 is 8
3.2 Random guessing
#! / bin / bash
# random generate a number between 1 and 3, and let you to
# guess the number ‘s value, if you are right, then echo "You guess right!"
# else echo "You guess wrong!"
# use while to play the game, input "quit" to quit the game
# $ RANDOM generate a number between 0 and 32767
while:
do
r = $ RANDOM
r = `expr $ r% 3 + 1` # between 1 and 3
echo "Please input a number between 1 and 10 (enter quit to quit the game):"
read g
if [[$ g = "quit"]]
then
break
elif [[$ g == $ r]]; then
echo "You guess right!"
else
echo "You guess wrong!"
fi
done
Output:
Please input a number between 1 and 10 (enter quit to quit the game):
2
You guess right!
Please input a number between 1 and 10 (enter quit to quit the game):
3
You guess right!
Please input a number between 1 and 10 (enter quit to quit the game):
3
You guess wrong!
Please input a number between 1 and 10 (enter quit to quit the game):
quit
3.3 Find the sum of all even numbers less than 100
#! / bin / bash
# sum the even number that less than 100
i = 2
s = 0
while [[$ i -lt 100]]; do
s = `expr $ s + $ i`
i = `expr $ i + 2`
done
echo "The even number that less than 100 ‘s sum is $ s"
Output:
The even number that less than 100 ‘s sum is 2450
3.4 Output asterisk (*) pyramid
#! / bin / bash
# output the pyramid of stars
for i in 4 3 2 1 0
do
j = $ i
while [[$ j -gt 0]]
do
echo -n ""
let "j--"
done
j = `expr 9-2 \ * $ i`
while [[$ j -gt 0]]
do
echo -n "*"
let "j--"
done
j = $ i
while [[$ j -gt 0]]
do
echo -n ""
let "j--"
done
echo ""
done
Output:
*
***
*****
*******
*********
Reference
Linux shell string operations (length, search, replace) detailed explanation
Linux shell array creation and use skills
(Experiment Building) Advanced bash scripting guide
Summary of basic shell operations
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.