Matthieu
Matthieu

Reputation: 16397

Creating a symbolic link in a bash script in a different folder

My bash script is getting two arguments with folders (that exist and everything).

Inside the first one I want to create a link to the second

Suppose I have the folders /home/matt/a and /home/matt/b, I call the script like this :

/home/matt # ./my_script ./a ./b

I want to see a symbolic link inside a that points to b

And of course, just doing

ln -s $2 $1/link

in the script does not work... (it will create a link that looks for a ./b inside a)

This is just a very simple example, I am looking for a script that will be generic enough to take different arguments (absolute or relative path...etc...)

Upvotes: 9

Views: 27045

Answers (3)

Dennis Williamson
Dennis Williamson

Reputation: 360085

Give this a try:

ln -s "$(readlink -e "$2")" "$1/link"

if you have readlink.

Or perhaps this variation on the answer by larsmans:

cd "$2"
dir=$(pwd)
cd -
ln -s "$dir" "$1/link"

Upvotes: 7

dogbane
dogbane

Reputation: 274612

Here's another cute one-liner:

ln -s `cd \`dirname $2\`; pwd`/`basename $2` $1/link

Upvotes: 1

Fred Foo
Fred Foo

Reputation: 363567

#!/bin/sh
cd $2
ln -s "`pwd`" $1/link

Upvotes: 1

Related Questions