6

I'm new in shell programming on macosx and have a little problem. I've written the following shell script:

#!/bin/sh

function createlink {
source_file=$1

target_file="~/$source_file"

if [[ -f $target_file ]]; then
    rm $target_file
fi

ln $source_file $target_file
}

createlink ".netrc"

When I'm executing this script I get the message ln: ~/.netrc: No such file or directory and I don't know why this happened! Do you see the error? Thanks!

Samveen
  • 3,482
  • 35
  • 52
Jan Baer
  • 1,105
  • 1
  • 12
  • 15
  • If run in your home directory, this script will first `rm` the named file and then fail to link to a file that isn't there. `if [[ $PWD == $HOME ]] ; then echo "error message"; exit 1; fi` should help you avoid that. – msw May 18 '13 at 12:49

1 Answers1

7

The issue is that tilde expansion will not happen as the path is in a variable value (tilde expansion happens before variable expansion). You can ameliorate this issue by using $HOME instead of ~. That is

target_file="${HOME}/${source_file}"

This should solve your problem.

Further reading: EXPANSION section of man bash

Samveen
  • 3,482
  • 35
  • 52