One-Day Study Shell : Part 1
The first Shell
- Create a new file “hello.sh”, write codes :
#!/bin/bash
echo "Hello Shell !"
- Run Shell:
cd
to the directory of the file "hello.sh"
执行Bash脚本文件方法:
chmod +x ./hello.sh
./hello.sh
第二种:
sh hello.sh
or
bash hello.sh
- Output:
Shell Variable
- Rule1: Only English,number(cannot be the first), and_
- Rule2: No space
- Rule3: No punctuation(,./~…)
- Rule4:No keywords in bash(
bash --help
)
Valid variable
KATHY
Kathy_Wang
_kathy
kathy16
Invalid variable
16kathy
?kathy
- Define variables
# no sapce between variable name and "="
name="kathy"
- Assign value to variable
#1.direct assign value
name="kathy"
#2.use statement
for file in $(ls /sys)
- Use variable :
echo $variable
name="kathy"
#Method 1
echo $name
#Method 2
echo ${name}
- Read-only variable
usereadonly
to set the variable to read-only variable, the value of read-only variable can not be changed
#!/bin/bash
name="kathy"
echo ${name}
readonly name
name="keke"
- Delete variable
unset variable_name
#!/bin/bash
name="kathy"
unset name
echo ${name}
- Variable types
1.Local variable
2.Environment variable
3.shell variable
Shell String
- Apostrophe
''
Just output in ‘’, cannot use variable
#!/bin/bash
name="kathy"
str='Your name is \"$name\"! \n'
echo $str
- Double quotes
'' ''
Can use variable and escape character
#!/bin/bash
name="kathy"
str="Your name is \"$name\"! \n"
echo $str
- Get string length
echo ${#string_name}
#!/bin/bash
str="name"
echo ${#str}
- Extract substring
echo ${string_name:from:to}
#!/bin/bash
str="What is your name?"
echo ${str:2:6}
- Find string `echo
expr index "$string_name" wanted_char
#!/bin/bash
str="What is your name?"
echo `expr index "$str" t`
Shell Array
bash supports just one-dimensional array(no multi-dimensional array), and there is no limit to the size of the array.
- Define array
array_name=(value0 value1 value2)
# Method1
array_name=(
value0
value1
value2
)
#Method2
array_name[0]=value0
array_name[1]=value1
array_name[2]=value2
- Read array
${array_name[index]}
Get all elements in array byecho ${array_name[@]}
#!/bin/bash
array_name=(name age school)
echo ${array_name[1]}
#!/bin/bash
array_name=(name age school)
echo ${array_name[@]}
- Get array length
${#array_name[@]}
#!/bin/bash
array_name=(name age school)
_1st_method_array_length=${#array_name[@]}
_2nd_method_array_length=${#array_name[*]}
single_element_length=${#array_name[2]}
echo ${_1st_method_array_length}
echo ${_2nd_method_array_length}
echo ${single_element_length}
Shell Comment
- Add
#
to each line
#-------------------------
#Name
#author:
#site:
#-------------------------
##### start #####
#
#
# some comments
##### end #####
- Multi-line comment
:<<EOF
Comment content...
Comment content...
Comment content...
EOF