0

I have a directory variable and function as follows:

coding_dir="~/Documents/coding"
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?

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

2 Answers 2

2

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 ; }
1
  • It was because I defined coding_dir after the alias. Simple oversight on my part. Thanks!
    – Kevin
    Commented Apr 2, 2018 at 23:18
-1

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.

You must log in to answer this question.

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