vim创建shell脚本时自动添加执行权限

前言

在Linux下编写shell脚本时,每次都要使用chmod +x 文件名的方式给文件赋予可执行权限,那有没有一种简单的方法,可以自动识别shell脚本并为其添加执行权限,经过网上搜索,发现可以配置vimrc来实现

步骤

[root@localhost chapter3]# vim ~/.vimrc
au BufWritePost * if getline(1) =~ "^#!" | if getline(1) =~ "/bin/" | silent !chmod +x <afile> | endif | endif
:wq
chmod +x ~/.vimrc

验证

# 创建demo.sh,什么都不输入,保存退出,这时候发现没有可执行权限
[root@localhost chapter3]# vim demo.sh   
:wq
[root@localhost chapter3]# ll
total 24
-rw-r--r--. 1 root root   0 May 31 23:00 demo.sh
-rwxr-xr-x. 1 root root 851 May 31 22:19 ex3-1.sh
-rwxr-xr-x. 1 root root 533 May 31 22:33 ex3-3.sh
-rwxr-xr-x. 1 root root  69 May 31 22:41 ex3-4.sh
-rwxr-xr-x. 1 root root 219 May 31 22:46 ex3-5.sh
-rwxr-xr-x. 1 root root 149 May 31 22:49 ex3-6.sh
-rwxr-xr-x. 1 root root  13 May 31 22:53 ex3-7.sh


# 只要第一行是以#!开头,且包含/bin/,配置就会自动的赋予可执行权限
[root@localhost chapter3]# vim demo.sh
#! /bin/bash
:wq
[root@localhost chapter3]# ll
total 28
-rwxr-xr-x. 1 root root  13 May 31 23:01 demo.sh
-rwxr-xr-x. 1 root root 851 May 31 22:19 ex3-1.sh
-rwxr-xr-x. 1 root root 533 May 31 22:33 ex3-3.sh
-rwxr-xr-x. 1 root root  69 May 31 22:41 ex3-4.sh
-rwxr-xr-x. 1 root root 219 May 31 22:46 ex3-5.sh
-rwxr-xr-x. 1 root root 149 May 31 22:49 ex3-6.sh
-rwxr-xr-x. 1 root root  13 May 31 22:53 ex3-7.sh

参考文章

《vim 创建.sh文件时,如何让其权限为744》

posted @ 2020-05-31 23:04  cnhkzyy  阅读(2065)  评论(0编辑  收藏  举报