2021-02-20Shell basic programming notes

1. Restart the disk to repair
fsck

Two, the declaration, reference and scope of variables in the Shell

变量赋值:等号两边不能有空格
如果要给变量赋空值,在等号后面跟换行符

显示变量的值
echo $variable
echo ${variable}

清除变量
unset variable

显示所有的变量
set

环境变量也就是全局变量,按规则要大写
export QUANJUBIANLIANG

3. Use of position parameters and command execution status codes in Shell programming

(脚本test.sh)
----------------------
# !/bin/bash
echo "Hello shell"
-----------------------
(1)执行脚本
. /test.sh
sh test.sh

(2)传递参数
----------------------
# !/bin/bash
echo "Hello $1 - $2 - $3 shell" # 传递三个参数
-----------------------
传递
./test.sh xiaoqing hadoop hdfs

Insert picture description here
4. Array, data and call commands in Shell commands

(1)数组定义和初始化
arr=(math english chinese)

(2)数组的引用
引用变量: ${arr[0]}
数组元素: ${arr[*]}
数组个数: ${#arr[*]}

(3)数组的赋值
arr[0]=Japanese

(4)编写输入日期的脚本
-------------------------------
date1=$(date +%Y-%m-%d)
echo date1
#  上式中“-”不是减去,而是连接的意思
date2=$(date --date='-1 days ago'  +%Y-%m-%d)
# 显示一天后的日期信息

(5)cal命令
cal 12 2020
#输出2020年12月的日历
-------------------------------

Five, the use of judgment expressions and if statements in Shell programming

栗子:
if [判断表达式]; then
    执行语句
 else # or elif
     执行语句
 fi  #结束if的执行,相当于end

判断表达式见下表:[]在表达式中可以代替test
栗子:
if [! -w "$HADOOP_LOG_DIR"] ; then
    mkdir -p "HADOOP_LOG_DIR"
fi

Insert picture description here
Insert picture description here

Six, the use of loop statements in Shell programming

(1)循环语句
for var in 12345
do
    echo ${var}
done
echo "- - - - - - - - - - - "
num=10
s=0
for((i=0;i<${num};i=i+1))
do
    s=$((${s}+${i})) # 因为要实现加法而不是连接,所以多了括号
done
echo${s}

(2)从命令行中逐行读取
cat ${file} | while read line # file例子:  ${SLAVE_FILE}
do
echo ${line}
done

Guess you like

Origin blog.csdn.net/tjjyqing/article/details/113890802