所以,我真的很喜欢文本编辑器这样的事实,例如Vim allows you to auto-write text (most of the times shebangs) when creating a new file with a specific file extension。
但是,我想知道是否有任何方法可以使用touch
命令从终端进行此操作。
例如,我想为我刚从终端创建的Python脚本自动生成shebangs,如下所示:
$ touch test.py # create file and auto-generate
$ cat test.py # see the contents to confirm
#!/usr/bin/env python
# -*- coding: utf-8 -*-
我知道我可以在我的环境中创建一堆自动生成的文本变量,例如PY_SHEBANG="#\!/usr/bin/env python\n# -*- coding: utf-8 -*-"
,只需执行:
$ echo $PY_SHEBANG > file.py
但是经历这么多麻烦的想法只会让我头晕目眩。
话虽如此:有没有办法配置终端/ shell,以便它可以识别我正在创建的文件的文件类型,并根据文件类型自动附加文本,只需一个 touch
命令?
注意:我使用的是zsh和oh-my-zsh。
答案 0 :(得分:1)
当然可以。只需使用别名并将touch
替换为我们自己编写的函数。但是我建议使用别名etouch
(增强触摸),所以如果你决定正常使用touch
命令,你可以。
由于您使用的是zsh,它会让事情变得更加轻松(但我想象它与bash类似)在.zshrc
(或.bashrc
,我不会&# 39;确切地知道),编写一个检查文件类型并输入任何内容的函数,如下所示:
# function for auto-generating shebang
function enhanced_touch () {
if [ -f $1 ]; then
echo "$1 already exists"
return 0
fi
if [[ $(echo -n "$1" | tail -c 3) == ".py" ]]; then
echo "#!/usr/bin/env python\n# -*- coding: utf-8 -*-" > $1
else
touch $1
fi
}
alias etouch="enhanced_touch"
显然,我只是按照你的要求定制了识别python文件的功能。但我会留下其他文件类型给你写。
另外,不要忘记source .zshrc
。祝你好运!