Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Writing Alias in a ZSH For Loop selects only the final loop iteration

I’m editing my .zshrc file to create aliases for different courses I’m taking at university. I currently do this for 5 courses:

alias 301='cd /Users/<...>/university/ELEC301'

Because all my courses have the same parent folder, I’m trying to do this as a for loop rather than having 10 lines of this same command with a different course code.

I have tried this but I end up getting an alias that only aliases to the last element of the array, despite my echo command printing what I expect:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

courses=(301 302 303)
for course in $courses; do
    echo $course
    alias $course='cd /Users/<...>/university/ELEC${course}'
done

In my ZSH terminal, when I run the alias 301, it consistently directs me to my 303 folder, or whichever is the final element of the array, despite my echo printing:

301
302
303

I’ve tried writing the array differently, changing the order of the echo, using an intermediate variable. I’m not sure what’s going on and appreciate the help.

>Solution :

By putting the variable course into single-quotes ' you prevent your shell from expanding it.

You need to use double-quotes " instead.

That:

courses=(301 302 303)
for course in $courses; do
    echo "$course"
    alias $course="cd /Users/<...>/university/ELEC$course"
done

would work fine.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading