Lec 2: Shell Script
变量命名
key=value #对空格敏感
key = value
#会报错,解释为执行key程序,输入两个arguments ‘=’ 和‘value‘’
echo "key is $key" #"key is value'
echo 'key is $key' #'key is key'
#单引号不会进行替换
$ 符号使用
$0 #Shell的文件名
$1 #第一个输入,同理$2,...,$9
$_ #获取最后一个argument
$? #返回上一个命令的结束代码,判断是否报错
$# #参数个数
$@ #参数列表,iterable
$$ #process id
var=$(pwd) #获取pwd输出并且赋值给var
.sh 文件编写与执行
例如在test.sh中写入
mcd(){
mkdir -p "$1"
cd "$1"
}
执行
source test.sh #在当前bash环境读取命令
#当前文件可以没有执行权限
mcd newdir#执行mcd()代码并传入参数
在example.sh 中写入
echo "Starting at $(date)"
echo "Running program $0 with $# arguments with pid $$"
for file in "$@"; do
grep foobar "$file" > /dev/null 2> /dev/null
#尝试找到foobar字符串,将输出扔到会被清空的
#特殊文件夹/dev/null,并将stderr 输出也扔掉
if [["$?" -ne 0]]; then
#如果error code != 0, 即没找到
echo "File $file does not have foobar, adding one"
echo "# foobar">>"$file"
fi
done
执行并传入参数
./example.sh mcd.sh example.sh
#甚至可以将自己传入参数
#./ 打开一个子shell来执行命令,可以并行运行多个脚本
脚本检查和debug
shellcheck example.sh
本文介绍了ShellScript中的变量命名规则,强调了对空格敏感性,$符号在命令行参数中的作用,如$0-$9、$_、$?、$@和$$等。还讲解了.sh文件编写、执行、参数传递以及如何使用shellcheck进行脚本检查和调试。

300

被折叠的 条评论
为什么被折叠?



