【LINUX】(shell)shell 脚本不完全笔记



1. 变量


1.1 默认变量

1.1.1 $1, $2, $3, ...

$1, $2, $3 … 等效于 C 语言的 argv[1], argv[2], argv[3], …


1.2 声明定义变量 - N/A



2. 逻辑条件 - 流程控制

2.1 if

  1. 判断命令(即“文件”)是否存在:

    不正确的写法:

    if [ -n "$(tree)" ]; then
    	tree
    else
    	ls
    fi
    

    正确的写法:

    if [ -f "/bin/tree" ]; then
    	tree
    else
    	ls
    fi
    
  2. 判断函数是否存在:

    #!/bin/bash
    
    #hello() {
    #	echo "Hello World"
    #}
    
    if [ -n "$(hello)" ]; then
    	hello
    else
    	echo "hello"
    fi
    
    exit 0
    

    虽然在 hello 函数不存在的情况下,终端会输出错误提示。
    不过 else 内的代码仍然会执行到。
    hello 函数存在的情况下(去掉注释),if 判断成立,会执行 if 条件成立下的 hello 函数。

  3. 判断文件/目录是否存在:

    判断文件:

    if [ -f "<file>" ]; then
    	echo "<file> exist"
    else
    	echo "<file> dosen't exist"
    fi
    

    判断目录:

    if [ -d "<folder>" ]; then
    	echo "<folder> exist"
    else
    	echo "<folder> dosen't exist"
    fi
    
  4. 判断变量 —— 字符串

    待补
    


3. 函数

3.1 定义函数

hello() {
	echo "Hello World"
}

3.2 调用/执行函数

直接输入函数名调用(见 line 8)

#!/bin/bash

[...]

hello() {
	...

hello

运行测试:

$ ./hello.sh
Hello World
$

含有参数的函数:

待补



4. 引用(库)

include

#!/bin/bash

include /lib/somepackage

[...]

库情况:

$ ls /lib/somepackage
somelib.sh      utils.sh    tools.sh   others.sh
...
$ 

source

$ ls
a.sh    b.sh
$ cat a.sh
#!/bin/bash

source b.sh


Reference



发布了164 篇原创文章 · 获赞 76 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/qq_29757283/article/details/100014559
今日推荐