简体   繁体   中英

Why doesn't “${0%/*}” work as expected on my machine?

let's assume this is 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

and file.sh exists in same folder next to test.sh the output will be

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

Is there some setting I'm missing?

It depends on how you are calling test.sh .

If you are calling it as ./test.sh or /path/to/test.sh , then
$0 will be ./test.sh or /path/to/test.sh respectively and
${0%/*} will be . or /path/to respectively.

If you are calling it as bash ./test.sh or bash /path/to/test.sh , then
$0 will be ./test.sh or /path/to/test.sh respectively and
${0%/*} will be . or /path/to respectively.

Above cases would work.

However, if you are calling it as cd /path/to; bash test.sh cd /path/to; bash test.sh , then $0 will be test.sh .

${0%/*} will remove everything from / . Your $0 does not have any / . So, it will remain unchanged. ${0%/*} will equal test.sh .
Hence ${0%/*}/foo.sh will be seen as non-existent.

Either you can use dirname "$0" or you can use below trivial logic:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM