文章目录
这节主要是bash作为脚本语言的一些基本用法,以及一些常见的功能强大的shell tools
Shell Scripting
可以用变量、循环、条件等更为复杂的方式,主要还是为了完成shell-related任务
变量
foo=bar # 将字符串bar赋值给变量foo
echo fool #这个会把fool理解为字符串
注意单引号和双引号是不一样的,单引号里面是字面量,不会进行变量替换;而双引号会替换
注意foo=bar
里是不能有空格的,如果有空格foo = bar
会理解为执行一个叫foo的程序,然后有参数=和bar,一般空格在shell里是来分割参数的
还可以将输出转化为变量 --> $(CMD)
foo=$(pwd)
echo $foo
echo "we are in $(pwd)"
另外<(CMD)
可以进行process substitution,执行命令,然后将结果放到一个临时文件里,再把这个<()
替换为临时文件
比如diff <(ls blogs) <(ls daily)
函数
vim mcd.sh
mcd () {
mkdir -p "$1"
cd "$1"
}
source mcd
mcd test
结果会新建一个test文件夹并进入
这里$1指的是第一个参数
-
$0
- Name of the script -
$1
to$9
- Arguments to the script. $1 is the first argument and so on. -
$@
- All the arguments -
$#
- Number of arguments -
$?
- Return code of the previous command,0表示没问题;true总是返回0,false总是返回1;grep查找没找到的时候也会返回1 -
$$
- Process identification number (PID) for the current script -
!!
- Entire last command, including arguments. A common pattern is to execute a command only for it to fail due to missing permissions; you can quickly re-execute the command with sudo by doing sudo !!-
比如mkdir xxxx发现没有权限,下一行可以直接sudo !!来替换这个路径
-
-
$_
- Last argument from the last command. If you are in an interactive shell, you can also quickly get this value by typing Esc followed by . or Alt+.
逻辑
false总是返回1,true总是返回错误码0.可以用|| &&来连接命令;另外;
总是会分割命令
false || echo "Oops, fail"
# Oops, fail
true || echo "Will not be printed"
#
true && echo "Things went well"
# Things went well
false && echo "Will not be printed"
#
true ; echo "This will always run"
# This will always run
false ; echo "This will always run"
# This will always run
分支
#!/bin/bash
echo "Starting program at $(date)" # Date will be substituted
echo "Running program