I have a directory variable and function as follows:

function f() { cd $1 && ls -a ; }

And I want to create an alias as follows:

alias rnd="f $coding_dir/random"

But when I try using the alias, I get the following error:

f:cd: no such file or directory: /random

I am aware I could just use the entire directory in the alias, but this was working when I was using bash. How do I get this to work in zsh?

  • 1
    You might need to first export coding_dir. – DopeGhoti Apr 2 '18 at 22:51
  • @DopeGhoti What does export do? – Kevin Apr 2 '18 at 23:16

Is it possible you're defining the alias before you set $coding_dir? From the error message, it looks like that's what's happening.

The issue is that you're expanding $coding_dir at the time when the alias is defined, not when it's used.

If you want it to expand it at usage time, then you should probably define it using single quotes, so that it will only expand $coding_dir when it's used.

alias rnd='f $coding_dir/random'

This will work even if you haven't defined $coding_dir yet and define it later:

$ coding_dir=~/Documents/coding
$ rnd
(should chdir to your $HOME/Documents/coding/random)

You might also want to add quotes to your alias, so that it handles directory names with spaces:

alias rnd='f "$coding_dir"/random'

And also in your definition of the f function:

function f() { cd "$1" && ls -a ; }
  • It was because I defined coding_dir after the alias. Simple oversight on my part. Thanks! – Kevin Apr 2 '18 at 23:18

The problem is caused by your usage of tilde combined with quotes. See for instance this transcript from my system:

-0-1- ~ > x="~/tmp"
-0-1- ~ > cd $x
cd: no such file or directory: ~/tmp
-1-1- ~ > y="$HOME/tmp"
-0-1- ~ > cd $y
-0-1- ~/tmp > cd ..
-0-1- ~ > z=~/tmp
-0-1- ~ > cd $z
-0-1- ~/tmp >

Your tilde won't be expanded, because it is placed within quotes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.