1

In .zsh, in my .zshrc file I'd like to set up a function to cd to a directory I input, but using an existing variable to write the common ~/path/to/parent/directory/$input

I've been unable to find out what the correct syntax is for this particular usage. For example, I want to enter

goto mydir

and execute a cd to ~/path/to/parent/directory/mydir

But I get an error: gt:cd:3 no such file or directory ~/path/to/parent/directory/mydir even though that directory exists.

This is the variable declaration and function I am trying:

export SITESPATH="~/path/to/parent/directory"

function gt(){
  echo "your site name is $@" 
  echo "SITESPATH: " $SITESPATH "\n"
  cd $SITESPATH/$@
}

It makes no difference if I use the above, without quotes, or "cd $SITESPATH/$@" with quotes.

2
  • Why is your question tagged with bash? Commented May 5, 2022 at 21:24
  • 1
    Not a direct answer to your question but maybe an option for you to avoid that function all together is the so called cdpath. Commented May 5, 2022 at 21:25

1 Answer 1

2

I don't see the point in using $@ in your function, since you expect only one argument. $1 would be sufficient.

The problem is in the tilde which is contained in your variable SITEPATH. You need to have it expanded. You can either do it by writing

export SITESPATH=~/path/to/parent/directory

when you define the variable, or inside your function by doing a

cd ${~SITESPATH)/$1

A third possibility is to turn on glob_subst in your shell:

setopt glob_subst

In this case, you can keep your current definition of $SITESPATH, and tilde-substitution will happen automatically.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. I'm just learning bash / zsh / she'll script writing so I'll make newbie mistakes like $@.
@MaxRocket : My personal recommendation for you as a newbie: Don't learn zsh and bash at the same time. The subtle but crucial differences will kill you. Stick with one of them (maybe zsh, since you now seem to focus on it anyway). Learn the other one after you have really mastered the first one.
not really trying to, just noting that there are overlaps. Primarily focused on .zsh at the moment. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.