Running MacOS High Sierra 10.13.5
Good day! Today I attempted to write a script in my .bash_profile
to allow me to call Sublime Text with a single command, sublime
.
Here is the script I produced with my limited knowledge of bash as well as some research:
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
I separated the function into two pieces for the sake of readability.
Expected Behavior:
sublime foo
opens an instance of Sublime to the file foo.txt, creating that file if it does not already exist.
Observed Behavior:
Bash returns:
line 29: syntax error: unexpected end of file
Note that line 29 is the line after the file's final line, which does not exist.
Attempts at solution:
So far I have searched for solutions here and here.
I have tried:
- Copying over to a new bash profile and deleting the old one to remove "ghost" characters
- Running dos2unix on my .bash_profile
- Parsing the script myself looking for individual errors, the problem seems to occur in the
sublime_open()
portion.
Sorry if my script is elementary or uninformed, this was my first attempt at writing a script that behaves this way. I welcome help or tips outside of the scope of my issue.
Thanks in advance!
Edit: Fixed misused heredoc as per @jwodder's solution as well as improper function calls as per @codeforester's solution.
Edit 2: If you are looking for a more elegant solution to this same problem, have a look at this very helpful gist.