toy
toy

Reputation: 12131

How can I create a symbolic link that depends on other files?

I know my topic is a little confusing, but here is what I want to do.

I have a file which I would like to create a link to in my home directory ~/bin, but when I execute the file that is symbolically linked, the file requires another file in its directory. Therefore, it fails to run because it cannot find the other file. What can I do?

Upvotes: 4

Views: 2146

Answers (4)

Lynch
Lynch

Reputation: 9474

I would rather create a script file in ~/bin/` that calls your executable from the appropriate directory.

Here is an example using /sbin/ifconfig:

$ cat > ~/bin/file
#!/bin/bash

file=/sbin/ifconfig
cd `dirname $file`
`basename $file` 
(ctr+d)
$ chmod +x ~/bin/file
$ file

Here you should see the output of ifconfig but the point is: its get executed from the /sbin directory. So if ifconfig had dependencies it would work properly. Just replace /sbin/ifconfig with your absolute path.

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246744

Combination of readlink and dirname will get the actual directory of the script:

my_dir=$(dirname "$(readlink -f "$0")")
source "$my_dir/other_file"

Upvotes: 0

Liangliang Zheng
Liangliang Zheng

Reputation: 1785

Alternatively, you can modify your script as

pushd ~/bin

##### your script here

popd

Upvotes: 0

matchew
matchew

Reputation: 19645

Well, you have two simple solutions.

  1. edit the shell script to point to the absolute path of the file, not just the the basename.

    ./path/to/file.sh VS file.sh

    so something like this should do what your after. sed -i 's|file.sh|./path/to/file.sh|g' ~/bin/script.sh it searches your symlinked file, script.sh in this case, and replaces the call to file.sh to ./path/to/file.sh. note you often see sed use /'s. but it can use just about anything as a delimiter, if you wish to use /'s here you will need to escape them. /. you may want to consider escaping the . (period) as well, but in this case its not necessary. If you are new to sed realize that the -i flag means it will edit the file in place. Lastly, realize its a simple search and replace operation and you may chose to do it by hand.

  2. The second way is to create a ln -s to the file as you did with the other file so there exists a symbolic link between both files.

    ln -s /far/off/script.sh ~/bin/script.sh

    and

    ln -s /far/off/file.sh ~/bin/file.sh

more on symlinking

Upvotes: 4

Related Questions