【问题标题】:Why doesn't "${0%/*}" work as expected on my machine?为什么“${0%/*}”在我的机器上没有按预期工作?
【发布时间】:2020-01-13 15:13:13
【问题描述】:

假设这是 test.sh

#!/bin/bash

if [ -f "file.sh" ]; then
    echo "File found!" # it will hit this line
else
    echo "File not found!"
fi

if [ -f "${0%/*}/file.sh" ]; then
    echo "File found!"
else
    echo "File not found!" # it will hit this line
fi

并且 file.sh 存在于 test.sh 旁边的同一文件夹中 输出将是

+ '[' -f file.sh ']'
+ echo 'File found!'
File found!
+ '[' -f test.sh/file.sh ']'
+ echo 'File not found!'
File not found!

我缺少一些设置吗?

【问题讨论】:

  • 你确定folder 存在吗?
  • 你在哪里运行它?在交互式 shell 中,$0-bash。尝试使用set -x 来查看您的命令扩展为什么。
  • 您使用它的上下文是什么?它是交互式的,还是在脚本中,如果它在脚本中,你是如何运行它的?你想通过使用${0%/*} 来完成什么?
  • 文件夹确实存在
  • 好吧,echo "${0%/*}/../folder" 打印什么?还可以使用 ex 调试您的脚本。 set -x 并查看(并发布)输出。

标签: windows bash unix path


【解决方案1】:

这取决于你如何打电话给test.sh

如果您将其称为./test.sh/path/to/test.sh,则
$0 将分别为./test.sh/path/to/test.sh
${0%/*} 将分别为./path/to分别。

如果您将其称为bash ./test.shbash /path/to/test.sh,则
$0 将分别为./test.sh/path/to/test.sh
${0%/*} 将分别为./path/to分别。

以上情况都可以。

但是,如果您将其称为cd /path/to; bash test.sh,则$0 将是test.sh

${0%/*} 将从/ 中删除所有内容。您的$0 没有任何/。因此,它将保持不变。 ${0%/*} 将等于 test.sh
因此${0%/*}/foo.sh 将被视为不存在。

您可以使用dirname "$0",也可以使用以下简单逻辑:

mydir=${0%/*}
[ "$mydir" == "$0" ] && mydir=.
if [ -f "$mydir/file.sh" ]; then
#... whatever you want to do later...

【讨论】:

    猜你喜欢
    • 2012-03-19
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    • 2021-08-19
    • 2017-12-26
    • 2019-08-28
    • 2014-10-18
    • 1970-01-01
    相关资源
    最近更新 更多