为什么“ $ {0%/ *}”在我的计算机上无法正常工作?

时间:2019-09-11 18:28:07

标签: windows bash unix path

假设这是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!

我缺少某些设置吗?

1 个答案:

答案 0 :(得分: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...