如果存在则打开文件,否则创建一个新文件并打开它

open file if it exists, otherwise, create a new one and open it

我目前设置了以下别名:

alias emacs='open -a Emacs'

但显然,如果该文件不存在,它会给我一个错误。有没有办法改变这个别名基本上说 "if the file exists open it in Emacs, otherwise, create the file and then open it in Emacs?"

谢谢!

使用函数而不是别名。函数可以做别名可以做的一切,甚至更多。

emacs() {
    if [ ! -f "" ]; then
        touch ""
    fi
    open -a Emacs ""
}

这应该适用于一个文件。对于多个文件,您可以使用它。

emacs() {
    for file; do
        if [ ! -f "$file" ]; then
            touch "$file"
        fi
    done
    open -a Emacs "$@"
}

您可以考虑为 open 命令使用带有 --args 选项的别名,如下所示:

alias emacs='open -a Emacs --args= '

然后将其命名为:

emacs $PWD/file.txt

根据man open

--args
     All remaining arguments are passed to the opened application in the argv parameter
     to main(). These arguments are not opened or interpreted by the open tool.

或者创建一个名为 omacs 的小脚本:

#!/bin/bash
for f in $*; do if [ -f $f ]; then open -a Emacs $f; else touch $f; open -a Emacs $f; fi; done

并创建这个别名

alias emacs='omacs'

处理多个文件。