【问题标题】:ln complains about no such file or directoryln 抱怨没有这样的文件或目录
【发布时间】:2013-05-13 10:33:13
【问题描述】:

我是 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 我不知道为什么会这样!你看到错误了吗?谢谢!

【问题讨论】:

  • 如果在您的主目录中运行,此脚本将首先rm 指定文件,然后无法链接到不存在的文件。 if [[ $PWD == $HOME ]] ; then echo "error message"; exit 1; fi 应该可以帮助您避免这种情况。

标签: bash macos shell variable-expansion tilde-expansion


【解决方案1】:

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

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

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

延伸阅读:EXPANSION部分man bash

【讨论】:

    猜你喜欢
    • 2020-02-04
    • 1970-01-01
    • 2021-06-24
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    相关资源
    最近更新 更多