Environment variables in symbolic links

2019-04-18 11:09发布

Can we use $HOME or other environment variable in symbolic links?

I know about using relative paths ../../.config but sometimes are to many ../ :) something like ~/.config would be more comfortable, or use of $HOME.

Edit:

habbie's answer with psmears's comment is the answer, sorry my question was incomplete.

While (as other answers show) you can use environment variables when creating symbolic links (as with any shell command!), you can't actually have environment variable (or '~') references in the symlink itself

标签: linux unix shell
5条回答
放荡不羁爱自由
2楼-- · 2019-04-18 11:31

Yes you can.

ln -s $HOME/file/or/folder newname

You can set your own variables and use them, too. Add in your .bashrc (or .bash_profile):

export $MYPATH=/your/path
查看更多
Melony?
3楼-- · 2019-04-18 11:39

If you don't want to expand the variable in the link you can put single quotes around it,

ln -s '$HOME/file/or/folder' newname

This would give,

newname -> $HOME/file/or/folder

rather than have it expand to your locally set $HOME. As described in other answers it will not expand it at all. So you can e.g. use it to symlink to a file inside the literal $HOME folder.

[Note this is system dependent - not all systems support variant symlinks]

查看更多
Rolldiameter
4楼-- · 2019-04-18 11:40

The closest I've been able to come is using a FUSE filesystem. It's pretty simple to use fusepy to write a custom passthrough filesystem, which can read environment variables when determining what real file to give. Of course, it only gets the environment variables of the process which mounted the passthrough system, so it's not as useful as it could be.

查看更多
Melony?
5楼-- · 2019-04-18 11:52

yes. no problem. actually you won't actually be using the $HOME variable in your link, so it won't work with smart solutions for groups of users for example. The variable is translated by the shell when executing the command, and the content of the variable is used in the link.

ln -s ~/test /tmp/test 

is expaned to

/<path>/<to>/home/test -> /tmp/test

Ah. and only the environment variables of the person calling ln will work. You can't store other peoples environment variables in the link. The variables are expanded before calling the command.

查看更多
We Are One
6楼-- · 2019-04-18 11:54

Symbolic links are handled by the kernel, and the kernel does not care about environment variables. So, no.

查看更多
登录 后发表回答