【发布时间】:2018-11-28 12:46:18
【问题描述】:
运行 MacOS High Sierra 10.13.5
美好的一天!今天我尝试在我的.bash_profile 中编写一个脚本,以允许我使用单个命令sublime 调用 Sublime Text。
以下是我以有限的 bash 知识以及一些研究制作的脚本:
sublime_open() # Function which opens the first argument as a text file in Sublime.
{
open -a /Applications/Sublime\ Text.app < $1.txt;
}
export -f sublime_open;
sublime_test() # Function which will open first argument as a text file in Sublime,
{ # creating one if it does not exist in the current directory.
if [ -e "$1" ];
then sublime_open "$1"
else
touch "$1".txt
sublime_open("$1")
fi
}
export -f sublime_test
alias sublime="sublime_test"
export sublime
为了便于阅读,我将函数分成两部分。
预期行为:
sublime foo 将 Sublime 实例打开到文件 foo.txt,如果该文件不存在,则创建该文件。
观察到的行为:
Bash 返回:
第 29 行:语法错误:文件意外结束
请注意,第 29 行是文件最后一行之后的行,不存在。
解决方案的尝试:
到目前为止,我已经搜索了解决方案 here 和 here。
我试过了:
- 复制到新的 bash 配置文件并删除旧的配置文件以删除“幽灵”字符
- 在我的 .bash_profile 上运行 dos2unix
- 自己解析脚本寻找个别错误,问题似乎出现在
sublime_open()部分。
对不起,如果我的脚本是基本的或不知情的,这是我第一次尝试编写这样的脚本。我欢迎超出我的问题范围的帮助或提示。
提前致谢!
编辑:修复了根据@jwodder 的解决方案误用的heredoc 以及根据@codeforester 的解决方案不正确的函数调用。
编辑 2:如果您正在为同样的问题寻找更优雅的解决方案,请查看 this very helpful gist.
【问题讨论】:
-
Shell 函数作为常规命令调用,例如
func arg1 arg2 ...而不是func(arg1, arg2, ...)。 -
在shellcheck检查您的代码。
-
你的heredoc没有结束标记。
-
您是否尝试过使用“subl”命令,该命令可在所有操作系统上安装 SublimeText 后使用(您可能需要设置二进制路径,以便从任何路径/文件夹运行此命令)?
-
@codeforester 刚刚修复了我的调用以匹配此语法。感谢您提供链接和提示!
标签: bash unix syntax sublimetext3