tags:

views:

40

answers:

3

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...)

+1  A: 
#!/bin/sh
cd $2
ln -s "`pwd`" $1/link
larsmans
it fails, looking for $1/link inside $2... right now, I am mostly trying by using only relative paths for both arguments...
Matthieu
Do you have pathnames with spaces in them? That might explain why it doesn't work without proper quoting (as exemplified by Dennis Williamson).
larsmans
+1  A: 

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"
Dennis Williamson
With readlink it works well (it's 'ln' instead of 'ls')
Matthieu
@Matthieu: Typo fixed, thanks.
Dennis Williamson
+1  A: 

Here's another cute one-liner:

ln -s `cd \`dirname $2\`; pwd`/`basename $2` $1/link
dogbane
I like that ...
Matthieu
You can avoid the awkward escaping by using `$()` instead of backticks: `ln -s "$(cd "$(dirname "$2")"; pwd)/$(basename "$2")" "$1/link"`
Dennis Williamson