linux编写脚本

发布时间 2023-10-09 00:11:37作者: HHHuskie

本文我使用自己常用的一个脚本做示范,该脚本的执行结果为同时输出本机的IP、网卡和DNS。将该脚本设置成命令后,则执行这一条命令得到本机的IP、网卡和DNS,正常情况下这三个结果分别需要执行一条命令才能得到,即一条命达到实现三条命令的效果。

1、编写shell脚本

这里可以是任何一个shell脚本,编写好后能够 通过bash执行即可

[root@localhost 720]# vim goip.sh
[root@localhost 720]# cat goip.sh
#! /bin/bash

# 获取ip
ip add |awk -F '[ /]+' '/ens33$/{print "ip:"$3}'
# 获取网关
ip route|awk 'NR==1 {print "geteway:"$3}'
# 获取DNS
awk 'NR!=1 {print "DNS:" $2}' /etc/resolv.conf

[root@localhost 720]# bash goip.sh
ip:192.168.10.129
geteway:192.168.10.2
DNS:114.114.114.114

2、授予脚本可执行权限

chmod 命令给该脚本文件授予可执行权限
授权后可以通过 ls -l 命令查看该文件是否具有x可执行文件
也可以通过 . / 来执行该文件

[root@localhost 720]# chmod +x goip.sh
[root@localhost 720]# ls -l goip.sh
-rwxr-xr-x 1 root root 193 7月  21 10:48 goip.sh
[root@localhost 720]# ./goip.sh
ip:192.168.10.129
geteway:192.168.10.2
DNS:114.114.114.114

 

3、复制脚本添加到PATH变量中

查看 PATH 变量,将脚本复制到其中的 /usr/bin 目录下

[root@localhost 720]# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
[root@localhost 720]# cp goip.sh  /usr/bin

4、定义命令别名

1、使用 alias 命令定义别名 goip ,即可在任意路径下执行该命令。
但是该方式仅支持在当前临时执行,重启后即失效了

[root@localhost 720]# alias goip='goip.sh'
[root@localhost ~]# goip
ip:192.168.10.129
geteway:192.168.10.2
DNS:114.114.114.114

2、修改 ~/. bashrc 脚本,添加 alias 命令进去,这样就可永久有效

[root@localhost ~]# vim ~/.bashrc
[root@localhost ~]# cat ~/.bashrc
# .bashrc

# User specific aliases and functions

alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
alias ls='ls --color=auto'
alias c='clear'
alias goip='goip.sh'
[root@wlf ~]# su - root
上一次登录:日 7月 24 17:30:50 CST 2022从 192.168.10.1pts/0 上
[root@localhost ~]# goip
ip:192.168.10.129
geteway:192.168.10.2
DNS:114.114.114.114

转自:https://blog.csdn.net/weixin_48693408/article/details/125961472