One of your problems is that you executed your snippet in a separate shell process, which has no effect on the parent shell. It's the same problem as in How can I make environment variables "exported" in a shell script stick around?How can I make environment variables "exported" in a shell script stick around?. You need to use the source
builtin (also avilable under the name .
) to execute the script inside the same shell.
source ~/.workspace-shotcuts.sh
Another problem is that you're trying to parse the output of ls
. Don't do that. In shells such as sh and bash, you can get away with it because writing $projects
outside of quotes splits the value at the newlines that separates the file names. Except that it doesn't actually work: for example, if the file names contain spaces, they will be broken into space-separated pieces. In a shell script, don't parse the output of ls
, use wildcards instead. This is rather straightforward in zsh.
projects=(~/Workspace/*/)
for f in $projects; do …
What you're doing next is rather convoluted. You don't need eval
here; using it only sets you up for quoting mishaps. Since you're using zsh, you can use the history modifier t
to extract the last component of a path, without reaching for string manipulation constructs: $f:t
. In case the file name contains special characters, you should protect them, and again zsh makes this easy thanks to the parameter expansion flag q
: ${(q)f}
gives you a quoted filename that you can use in the alias definition.
projects=(~/Workspace/*/)
for f in $projects
do
alias $f:t="cd ${(q)f}"
done
But in fact, you're just reinventing cdpath
plus auto_cd
. Scratch all that and use
setopt auto_cd
cdpath+=~/Workspace
The auto_cd
option lets you type a directory name to change into it, without having to type cd
before it. The cdpath
is an array of directory prefixes that cd foo
tries if there isn't a subdirectory called foo
in the current directory.
In case bash users see this thread: the alias method would be
projects=(~/Workspace/*/)
for f in "${projects[@]}"; do
f=${f%/}
alias ${f##*/}="cd '${f//\'/\'\\\'\'}'"
done
and the CDPATH
method would be
CDPATH=$CDPATH:$HOME/Workspace
shopt -s autocd