0

I'm trying to modify my .bash_profile which currently looks like:

alias kx="kubectx"
gcreds () {
gcloud container clusters get-credentials $1 --zone $2;
}

however when i try to :wq and source .bash_profile (in a mac os x terminal) i get the following error message:

bash: .bash_profile: line 14: syntax error near unexpected token `('
-bash: .bash_profile: line 14: `gcreds (){'

a colleague also tested the same (in an iterm terminal) and was able to run the function with no errors

any ideas what i could be doing wrong?

1

1 Answer 1

1

Hypothesis: In your (but not in your colleague's) shell gcreds is an alias defined before the troublesome line is parsed.

Alias expansion happens early and it's purely textual (i.e. gcreds string gets replaced by some string, no logic there). Your definition of the function becomes invalid, probably because () is not after the very first word. E.g. if gcreds was replaced by gcreds --something then it would be:

gcreds --something () { …

which is not a syntactically valid definition of a function. But it may be gcreds gets replaced by something else:

something-else-than-gcreds whatever and more () { …

It doesn't matter what the replacement is. The fact () is now in the wrong place matters.

In Bash you can run type gcreds to see what gcreds really is. Also try type -a gcreds (and help type to learn what -a does).

You can define a function in an alternative way, without ():

function gcreds { …

This syntax is not portable. I understand you're going to use it inside ~/.bash_profile which is a Bash-specific file, so it's OK.

Now the first word is function. I assume it's not aliased and it's interpreted as a keyword (check type function). If so, the gcreds alias is not expanded when the definition is parsed, it cannot break the definition. This way you can define a function named gcreds, even if there's already a gcreds alias.

Suppose you manage to define gcreds alias and gcreds function. Now if you run gcreds foo bar and your alias replaces gcreds with gcreds … then the alias will be expanded first, the function will be executed later. But if your alias replaces gcreds with something-else-than-gcreds … then the alias will be expanded first, the function won't matter (a function named something-else-than-gcreds would mater, if any).

You probably don't need an alias and a function with the same name. Pick one. If you do need them both, define the function first, the alias later; or use the keyword function as shown above.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .