ITeye博客

Bash简要入门

rensanning · 2018-01-19 16:03 · Linux · 编程语言 · Markdown

(一)Shell 和 Bash

Bash(Bourne-Again SHell)Linux系统默认的命令解释器。

[root@localhost ~]# file -h /bin/sh
/bin/sh: symbolic link to `bash'
[root@localhost ~]# echo $SHELL
/bin/bash

Stephen Bourne创建了Bourne Shell(即sh),之后Brian Fox 开发了 Bash,它是Bourne Shell的扩展。除过Bash外还有很多Shell解释器:Korn Shell (ksh) 、C Shell (csh) 、Tenex C Shell (tcsh) 、Almquist (ash)、Bourne Again Shell (bash)、Z shell (zsh)等。

(二)Shell分类

(1) 交互式Interactive Shell 一般打开terminal后自动进入交互式sh。可以输入/编辑命令然后回车执行,Linux采用Bash作为默认的命令解释器。

[root@localhost ~]# echo "Hello World"
Hello World

echo就是Bash的内建命令,它会输出信息并换行。

(2) 非交互式Non-Interactive Shell 如果shell不需要人为的输入任何东西时,可以创建脚本文件,文件里可以用任何的命令。

[root@localhost ~]# vi hello-world.sh
#!/bin/bash
echo "Hello World"
[root@localhost ~]# chmod +x hello-world.sh
[root@localhost ~]# ./hello-world.sh
Hello World

执行脚本文件的方法:

# ./hello-world.sh (一般是这种)
# /root/hello-world.sh
# /bin/bash hello-world.sh
# bash hello-world.sh
# sh hello-world.sh

Shell脚本文件的第一行注明了用什么解释器来解释这个脚本。 比如:

#!/bin/csh
#!/bin/bash

在很多系统里/bin/bash是不存在的,比如变成了/usr/local/bin/bash,为了避免路径的问题可以使用环境变量:

#!/usr/bin/env bash

Shell脚本文件一般后缀为.sh(Linux里文件扩展名没有任何意义)

Shell脚本文件如果是在Window下编写,需要注意修改文件内部的换行符 dos2unix hello-world.sh

[root@localhost ~]# ./test-win-sh.sh
-bash: ./test.sh: /bin/bash^M: bad interpreter: No such file or director
[root@localhost ~]# dos2unix test-win-sh.sh
dos2unix: converting file test-win-sh.sh to UNIX format ...
[root@localhost ~]# ./test-win-sh.sh
Hello World2

(三)变量

#!/usr/bin/env bash
# 定义变量。
# 注意等号两边不能有空格,不然会把变量名当做命令执行。
whom_variable="rensanning"
# 打印输出变量值。$+变量名。双引号里的变量会被解析,单引号会原样输出。
printf "Hello, $whom_variable\n"

*** 注释以#号开头,但第一行的#!不是注释,它代表bash解释器的路径。

命令行参数

$#: 参数个数 $@: 所有参数数组 $0: 当前脚本 $1: 第一个参数 $2:第二个参数 以此类推 ${10}: 第10个参数开始需要大括号 $?: 前一个命令的返回值

内置变量

$HOME : 用户目录 $PWD : 当前目录 $PATH : 环境变量PATH

(四)引号

双引号"..." : 解析$、\、的值 单引号'...' : 包含空格的字符串。(两个单引号之间不能使用单引号) 反引号...` : 作为命令执行

(五)括号

(1) 小括号 ( command1; command2 ) Command group executed within a subshell
Array=(element1 element2 element3) Array initialization
result=$(COMMAND) Command substitution, new style

(COMMAND) Process substitution
<(COMMAND) Process substitution (( var = 78 )) Integer arithmetic
var=$(( 20 + 5 )) Integer arithmetic, with variable assignment (( var++ )) C-style variable increment
(( var-- )) C-style variable decrement
(( var0 = var1<98?9:21 )) C-style ternary operation

(2) 中括号 (test 和 等价) if Test construct
if ] Extended test construct &&, ||, Pattern matching, 正規表現などが使える。 Array=element1 Array initialization
Range of characters within a Regular Expression $ A non-standard & obsolete version of $(( expression ))

(3) 大括号 ${variable} Parameter substitution
${!variable} Indirect variable reference
${#str_var} Length of $str_var { command1; command2; . . . commandN; } Block of code
{string1,string2,string3,...} Brace expansion
{a..z} Extended brace expansion
{} Text replacement, after find and xargs

(六)数组

arr1=(1 2 3 4)
arr2=('first element' 'second element' 'third element')
arr2[0]='first'
arr2+=('fourth element' 'fifth element')
echo "${arr2[0]}"
arr3=("${arr1[@]}" "${arr2[@]}")
echo "${#arr3[@]}"

(七)控制语句

(1) IF语句

if [[ $1 -eq 1 ]]; then
  echo "1 was passed in the first parameter"
elif [[ $1 -gt 2 ]]; then
 echo "2 was not passed in the first parameter"
else
  echo "The first parameter was not 1 and is not more than 2."
fi

*** 注意 前后必须有空格。 *** 如果then 和 if 在一行时需要分号,then在下一行的话就可以省略分号。

(2) FOR语句

for i in "${arr[@]}"; do
  echo "$i"
done
for ((i=0;i<${#arr[@]};i++)); do
  echo "${arr[$i]}"
done

break # exit n levels of loop continue # go to next iteration of loop n up

(3) WHILE语句

i=0
while [ $i -lt ${#arr[@]} ]; do
  echo "${arr[$i]}"
  i=$(expr $i + 1)
done
i=0
while (( $i < ${#arr[@]} )); do
  echo "${arr[$i]}"
  ((i++))
done

(4) CASE语句

case "$BASH_VERSION" in
  [34]*)
    echo {1..4}
    ;;
  *)
    seq -s" " 1 4
esac

(八)函数

# 定义函数
function hello() {
  echo "hello, rensanning"
}
# 定义函数(省略function)
greet () {
  echo "Hello World!"
}
# 调用函数
greet
# 本地变量
greet() {
  var="Global"
  local name="rensanning"
  echo "Hello, $name"
}
greet
echo $var
echo $name
# 函数参数
greet() {
  echo "Hello, $1"
}
greet "rensanning"
# 返回值
fun() {
 local var="Sample value to be returned"
 echo "$var"
}
var="$(fun)"

参考: https://linuxconfig.org/bash-scripting-tutorial-for-beginners

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。