6

我是 macosx 上的 shell 编程新手,有一点问题。我编写了以下 shell 脚本:

#!/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"

当我执行此脚本时,我收到消息ln: ~/.netrc: No such file or directory我不知道为什么会这样!你看到错误了吗?谢谢!

4

1 回答 1

7

问题是这tilde expansion不会发生,因为路径在变量值中(tilde expansion发生在之前variable expansion)。您可以通过使用$HOME代替来改善此问题~。那是

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

这应该可以解决您的问题。

延伸阅读:EXPANSION部分man bash

于 2013-05-18T09:57:43.163 回答