Linux Shell脚本知识点

it2024-04-07  73

说明:此为按照野火Linux教程学习时记录的shell的知识点。

查看系统支持的shell

/etc/shells文件记录支持的shell,可通过cat指令查看。

book@100ask:~$ cat /etc/shells # /etc/shells: valid login shells /bin/sh /bin/bash /bin/rbash /bin/dash

查看是否是内建命令(type命令)

book@100ask:~$ type pwd pwd is a shell builtin #pwd是内建命令 book@100ask:~$ type ifconfig ifconfig is /sbin/ifconfig

#!/bin/bash

shell脚本开头固定内容,用于指定脚本的解析器

定义变量

变量赋值“=”两边不能有空格

variable=value value中不能有空格,如需要空格,需要用引号括起整个变量值variable=“value” 双引号内 $ 引用的变量会被展开variable=‘value’ 单引号内的内容直接作为变量值,不会被展开

使用变量

$variable${variable} var=1234 var="12 34" var1="$var" #var1 的值为: 12 34. $后的变量值会被展开引用 var2='$var' #var2的值为:$var $没有展开 var1="${var}abc" #var1的值为: 12 34abc var1="$varabc" #var1为空值,没有varabc这个变量

删除变量 unset

usent var

命令结果赋值给变量

variable=commandvariable=$(command) var=`pwd` var1=$(pwd) # var var1的输出都是当前shell脚本所在目录

特殊变量$0 $n $* $#

变量含义$0shell脚本的名字$n传递给shell脚本的参数,n表示第几个参数(n>0).如$1表示第一个参数,$2表示第2个参数$#传递给shell脚本的参数的个数$*传递给shell脚本的所有参数,若用""括起,表示所有参数整体,否则表示一个一个参数。for in $*,单个参数的输出;for in "$*",所有参数作为整体输出,参数之间有空格$@传递给shell脚本的所有参数,加不加""结果都一样$?上个命令的执行结果或者退出状态$$当前shell进程ID #1.执行成功 book@100ask:~$ pwd /home/book book@100ask:~$ echo $? 0 #2.执行失败 book@100ask:~$ cd /unexist bash: cd: /unexist: No such file or directory book@100ask:~$ echo $? 1 #3.shell脚本中exit exit 10 echo $? 10

读取键盘输入

read -p "input a:" a read -p "input b:" b

整数数学运算 (())

a=10 b=20 sum=$((a+b)) #sum的值为30

逻辑 && 、||

command1 && command2 command1 || command2

&& 上一个命令执行成功或者成立才会执行后边的命令|| 上一个命令执行失败或者不成立才会执行后边的命令

检测某个条件是否成立 test expression 或者 [ expression ]

a=3 b=3 #1.输出 a=b test $a -eq $b && echo "a=b" #2.输出 a=b 注意: [] 内部两边要有空格 [ $a -eq $b ] && echo "a=b" #3.什么都不输出. test $a -eq $b || echo "a=b" a=3 b=4 #4.输出 a!=b test $a -eq $b || echo "a!=b" 项目含义-eq相等-ne不等-gt大于-lt小于-ge大于等于-le小于等于-z str判断str是否为空-n str判断str是否为非空-d dir判断目录dir是否存在。如 [ -d /etc ] && echo “/etc”-d file判断文件file是否存在

管道 |

command1 | command2 将command1命令的输出信息传递给下一个命令,作为command2命令的输入。

if、elif、else 命令

if condition then statemnent fi # fi作为if语句的结束

如:

a=3 b=3 if [ $a -eq $b ] then echo "a=b" elif [ $a -gt $b ] then echo "a>b" else echo "a<b" fi

case in

read -p "input a:" a case $a in 1) echo "a=1" ;; 2) echo "a=2" ;; *) echo "other value" ;; esac

for in

#1. for n in 1 2 3 4 5 #for n in {1..6} do echo "$n" done #2.引用命令执行结果 for n in $(ls /bin/*sh) do echo "$n" done #输出ls的结果

"$" 与 $* 区别

book@100ask:~$ cat test.sh #!/bin/bash echo 'the $* output:' for n in $* do echo $n done echo 'the "$*" output:' for n in "$*" do echo $n done book@100ask:~$ ./test.sh 1 2 3 the $* output: 1 2 3 the "$*" output: 1 2 3

while

n=0 while ((n<3)) do echo $n n=$((n+1)) done

函数

function myname(){ echo "myname" } #调用函数 myname
最新回复(0)