假设这是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!
我缺少某些设置吗?
答案 0 :(得分:1)
这取决于您如何呼叫test.sh
。
如果您将其称为./test.sh
或/path/to/test.sh
,则
$0
将分别为./test.sh
或/path/to/test.sh
,并且
${0%/*}
将分别为.
或/path/to
。
如果您将其称为bash ./test.sh
或bash /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...