With Bash scripting, is there a way to determine which directory a link is pointing to, then switch it to another directory based on the result?
For example, say I have the two following directories:
/var/data/1/
and /var/data/2/
I have a link to one of them, say, dat开发者_StackOverflow社区a_link
and it is currently linked to /var/data/1/
When the script is triggered, I want it to swap the link to /var/data/2/
(i.e. ln -s /var/data/2/ /somepath/data_link
).
When the script is triggered again, the opposite will happen (i.e. ln -s /var/data/1/ /somepath/data_link
), and so on. What's the easiest way to do this via a Bash script?
Unfortunately, the standard set of unix utilities doesn't include an easy access to the readlink
system call. Some systems include a readlink
command. If it's available, there's a good chance that readlink foo
prints the target of the symlink foo
. If you feel tempted to use options, be warned that there are multiple versions of this command floating around; you won't get portability even between Linux distributions.
If you have perl available, perl -e 'print readlink $ARGV[0]' mylink
prints the target of mylink
.
If you need a portable way and don't have Perl or anything else sane, you can perhaps make do with parsing the output of ls -l mylink
.
If you have a symbolic link to a directory that you have permission to change into, then $(cd mylink && command -p pwd)
is the absolute path to the ultimate target of the link. For example, if foo
is a symlink to /var/tmp/bar
, bar
is a directory in /var/tmp
and /var/tmp
is a symbolic link to /tmp
, this command yields /tmp/bar
.
Use the readlink
command to get the content of a link:
$TARGET=$(readlink "$LINK")
Then use standard if
to inspect the current value, rm
to remove it, and ln
as you indicated to re-create with the new desired target.
精彩评论