shell实战_函数和别名概念

发布时间 2023-10-10 11:02:26作者: WeChat2834
shell函数
  • 函数,就是将你需要执行的shell命令,组合起来,组合成一个函数体
  • 还得给这个函数体起了一个名字,这个名称就是函数名
  • 函数就是函数名称+函数体
  • 以后想执行这个函数,直接使用函数名字即可。
别名

别名的功能简化功能操作,使命令更加的易读

[root@localhost tmp]# alias myll="ls -lah ./"      ###新建的别名只能在当前进程,如果要持久化,应该要加配置文件
[root@localhost tmp]# myll
总用量 112K
drwxr-xr-x.  6 root root 4.0K 10月  7 15:20 .
dr-xr-x---. 17 root root 4.0K 10月  8 09:52 ..
-rw-r--r--.  1 root root  253 9月   5 15:48 !
-rw-r--r--.  1 root root   27 9月  19 14:41 calcualation2.sh
-rw-r--r--.  1 root root    0 9月  25 15:57 风景.jpg
[root@localhost tmp]# ls -lah
总用量 112K
drwxr-xr-x.  6 root root 4.0K 10月  7 15:20 .
dr-xr-x---. 17 root root 4.0K 10月  8 09:52 ..
-rw-r--r--.  1 root root  253 9月   5 15:48 !
-rw-r--r--.  1 root root   27 9月  19 14:41 calcualation2.sh
-rw-r--r--.  1 root root    0 9月  25 15:57 风景.jpg
[root@localhost tmp]# 
############直接输入命令,可把当前系统别名都展示出来
[root@localhost tmp]# alias
alias cp='cp -i'
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'
alias grep='grep --color=auto'
alias l.='ls -d .* --color=auto'
alias ll='ls -l --color=auto'
alias ls='ls --color=auto'
alias mv='mv -i'
alias myll='ls -lah ./'
alias rm='rm -i'
alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde'
[root@localhost tmp]# 


函数的优点
  1. 将相同的程序,定义,封装为一个函数,能减少程序的代码数量,提供开发效率
  2. 使用函数,能让你写更少的代码,
  3. 函数能增加程序的可读性,易读性,容易管理
函数的语法

简化版函数的定义和使用

定义函数

花括号的里面就是函数体,写入shell命令即可

sayHello(){

echo "hello,world"

}

调用函数,执行函数

sayHello