系统相关
首页 > 系统相关> > 【Missing Semester】Shell工具和脚本

【Missing Semester】Shell工具和脚本

作者:互联网

本文为计算机教育中缺失的一课 The Missing Semester of Your CS Education 笔记


Shell 脚本

第一个 Shell 脚本:


变量


字符串


数组

例——变量、字符串、数组:

#!/bin/bash
var1="Hello"
echo $var1
echo "double quote" "$var1"
echo "single quote" '$var1'
var2=("Monday" "Tuesday" "Wednesday")
echo "lenth of array" ${#var2[@]}
echo "lenth of first element" ${#var2[0]}

# 输出
# Hello
# double quote Hello
# single quote $var1
# lenth of array 3
# lenth of first element 6

传递参数

例——传递参数:

echo "-- \$* 演示 ---"
for i in "$*"; do
echo $i
done

echo "-- \$@ 演示 ---"
for i in "$@"; do
echo $i
done

echo "$0"
echo "$#"

执行结果:

bogon:tmp wangxinyuan$ ./a.sh hhh w x y
-- $* 演示 ---
hhh w x y
-- $@ 演示 ---
hhh
w
x
y
./a.sh
4
bogon:tmp wangxinyuan$ echo "$?"
0

运算符

算数运算符:

关系运算符:

布尔运算符:

逻辑运算符:

字符串运算符:

文件测试运算符:咕咕咕~


流程控制

if else:

if condition1
then
    command1
elif condition2 
then 
    command2
else
    commandN
fi

for:

for var in item1 item2 ... itemN
do
    command1
    command2
    ...
    commandN
done

while:

while condition
do
    command
done

until、case esac、break、continue:咕咕咕~


函数

[ function ] funname [()]
{
    action;
    [return int;]
}

其它

例——命令替换、通配:

#!/bin/bash

echo "Starting program at $(date)"						# 命令替换
echo "Running program $0 with $# arguments with pid $$"

for file in "$@"
do
    # 如果模式没有找到,则grep退出状态为 1
    # 我们将标准输出流和标准错误流重定向到Null,因为我们并不关心这些信息
    grep foobar "$file" > /dev/null 2> /dev/null
    if [[ $? -ne 0 ]]
    then
        echo "File $file does not have any foobar, adding one"
        echo "# foobar" >> "$file"
    fi
done

执行结果:

bogon:tmp wangxinyuan$ touch text{1,2,3,4,5}.txt		# 通配
bogon:tmp wangxinyuan$ echo "# foobar" > text3.txt
bogon:tmp wangxinyuan$ ./a.sh text{1,2,3,4,5}.txt
Starting program at 2022年 2月19日 星期六 15时20分19秒 CST
Running program ./a.sh with 5 arguments with pid 19714
File text1.txt does not have any foobar, adding one
File text2.txt does not have any foobar, adding one
File text4.txt does not have any foobar, adding one
File text5.txt does not have any foobar, adding one

Shell 工具


文件管理


文档编辑


磁盘管理


参考

标签:文件,Shell,Missing,echo,运算符,Semester,sh,字符串
来源: https://www.cnblogs.com/wxy4869/p/15913419.html