How to write Shell script

How to write Shell script

Here you can get to know the basic grammar of shell quickly

I. Shell variable

i. Valid format of variable
1
2
3
4
NAME
LD_LIBTARY_PATH
_var
var2
ii. How to use the variable
1
2
3
4
5
6
7
var="this is a variable"
echo $var
#Set the var read only
readonly var
echo ${var}
#delete the var
unset var

It’s a good habit to have a pair of brace

II. Shell string

i. joint string
1
2
3
var1="ruboob"
var2='great'
greeting="${var1},${var2}"
ii. Operation string
1
2
3
4
5
6
7
8
9
10
string="abcdefg"
#get the length of the string
echo ${#string}
#get the four chars of string start from index 1, Attention: index start from 0
echo ${string:1:4} #get "unoo"
var="This is a string"
echo ${string#*s} #s is a string
echo ${string##*s} #tring
echo ${string%s*} #This is a
echo ${string%%s*} #Thi

Search the string

1
2
3
string="abcdefghijkl"
#print the first index of char 'i'
echo `expr index "${string} i"`

III. Shell array

i. Declare an array
1
2
3
4
5
6
#Attention : no comma inside
array_name1=(value0 value1 value2 value3)
#or
array_name2[0]=value0
array_name2[1]=value1
array_name2[2]=value2
ii. Operation array
1
2
3
4
5
6
7
8
array_value=${array_name1[n]}
#get all elements of the array
echo ${array_name1[@]}
#get the length of the array
length=${#array_name[@]}
length=${#array_name[*]}
#get the length of the first element of array
length=${#array_name[0]}

IV. Shell Comment

1
2
3
4
5
6
7
8
# This is a comment line

:<<EOF
This is a
triple-line
comment
EOF
# 'EOF' here can be replaced by any other symbol (like ', !)

V. Shell parameter

1
2
3
4
5
6
7
8
9
$ bash ./shell.sh 1 2 3
$0 : the file name of shell
$1 : 1
$2 : 2
$3 : 3
$# : 3 # the number the parameter
$* : show all the parameters as a string
$@ : some as $*
$? : show the status of the last command

VI. Shell Operator

1
2
3
4
5
6
7
8
9
10
11
12
13
var=`expr 2 + 2`
var=$(expr 2 + 2)
var=`expr 2 \* 3`
a=10
b=20
if [ $a != $b -a $b -gt $(expr $a - $b) ];then
echo "hi"
fi
string=""
if [ -n "$string" ]
echo "The length of the string is 0"
fi
[[ && || > < ]]

How to write Shell script
https://dtover.github.io/2020/07/17/How-to-write-Shell-script/
作者
John Doe
发布于
2020年7月17日
许可协议