[英]Why doesn't “${0%/*}” work as expected on my machine?
让我们假设这是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!
我缺少某些设置吗?
这取决于您如何调用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
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...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.