bash - ln 提示没有这样的文件或目录

标签 bash macos shell variable-expansion tilde-expansion

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

最佳答案

问题是 波浪号扩展 不会发生,因为路径在变量值中(波浪号扩展 发生在 变量扩展 之前)。您可以使用 $HOME 而不是 ~ 来改善这个问题。也就是

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

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

进一步阅读:man bashEXPANSION 部分

关于bash - ln 提示没有这样的文件或目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16622899/

相关文章:

BASH - 使用 LS 和通配符的 FOR 循环

bash - 如何查找字符串并将其替换为引号?

php - 如何修复 PHP 警告 : Unable to load dynamic library: php_intl. ddl

macos - 轮询 MacBook Pro 中的加速计/运动传感器

python - 如何获取 Mac 应用程序的 Bundle ID?

C++ ShellExecute特殊字符

linux - 用于查找第 n 次出现的字符串并打印行号的 shell 脚本

bash - 羊群权限被拒绝 bash

linux脚本简单算术代码

bash - 在 Unix shell 中,如何以机器字节顺序将十六进制字符串转换为标准输出字节