【大数据】-shell快学01

137 阅读1分钟

一、shell简介

Shell 就是一种脚本语言,我们编写完源码后不用编译,直接运行源码即可。脚本语言的优点是使用灵活、部署容易、跨平台性好,非常适合 Web 开发以及小工具的制作。

image.png

二、大数据组件中shell示例

所以我们发现很多开源的大数据组件都是通过shell脚本进行操作的。比如Kafka, Flink等。一般都是放在对应的bin目录下。如/kafka_2.12-2.8.2/bin

image.png

查看下topic操作的shell:
[root@node6 bin]# vim kafka-topics.sh

#!/bin/bash
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
# 
#    http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

exec $(dirname $0)/kafka-run-class.sh kafka.admin.TopicCommand "$@"
~                                                                          

最后调用的是kafka-run-class.sh, 传入了参数 kafka.admin.TopicCommand,$@。 这里的$@代表是所有参数。

[root@node6 bin]# vim kafka-run-class.sh
image.png

shell的最后是执行具体的命令:

  nohup "$JAVA" $KAFKA_HEAP_OPTS $KAFKA_JVM_PERFORMANCE_OPTS $KAFKA_GC_LOG_OPTS $KAFKA_JMX_OPTS $KAFKA_LOG4J_OPTS -cp "$CLASSPATH" $KAFKA_OPTS "$@" > "$CONSOLE_OUTPUT_FILE" 2>&1 < /dev/null &
else
  exec "$JAVA" $KAFKA_HEAP_OPTS $KAFKA_JVM_PERFORMANCE_OPTS $KAFKA_GC_LOG_OPTS $KAFKA_JMX_OPTS $KAFKA_LOG4J_OPTS -cp "$CLASSPATH" $KAFKA_OPTS "$@"
fi

三、shell特殊变量的说明

这节我们重点学习下shell中的特殊命令,这是我们在大数据的开源shell脚本中,经常会遇到的,了解其含义有利于我们更好的学习看懂这些代码。

前面提到了$@,下面列举常见的一些:

变量含义
$0当前脚本的文件名。
$n(n≥1)传递给脚本或函数的参数。n 是一个数字,表示第几个参数。例如,第一个参数是 1,第二个参数是1,第二个参数是 2。
$#传递给脚本或函数的参数个数。
$*传递给脚本或函数的所有参数。
$@传递给脚本或函数的所有参数。
$?上个命令的退出状态,或函数的返回值。
$$当前 Shell 进程 ID。对于 Shell 脚本,就是这些脚本所在的进程 ID。

当 $* 和 $@ 不被双引号" "包围时,它们之间没有任何区别,都是将接收到的每个参数看做一份数据,彼此之间以空格来分隔。

但是当它们被双引号" "包含时,就会有区别了:

  • "$*"会将所有的参数从整体上看做一个整体,而不是把每个参数都看做一个整体。
  • "$@"仍然将每个参数都看作一个整体,彼此之间是独立的。