0

I'm trying to modify someones script, and there's a certain part of it that's really confusing to me. It looks like below.

if [[ ! -f "${0%/*}/somefile" ]]; then
    echo "Cannot find somefile, quiting..." >&2
    exit 1
else
    source "${0%/*}/somefile"
fi

I know it's checking for the existence of a file, and using this code ${0%/*} to try to get the current directory, however it doesn't run for me. My way of fixing it was to replace it with pwd which works much better.

I'm just wondering if anyone could elaborate to me as to what that portion of the code ${0%/*} was trying to do?

Joshua Strot
  • 2,343
  • 4
  • 26
  • 33

1 Answers1

2

It's not trying to get the current directory, it's trying to get the directory that contains the script. $0 is the name of the script, and the %/* modifier removes everything from the last / in it.

This script expects somefile to exist in the same directory that the script is installed in, not your current directory.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Oh wow, I feel stupid now. Thanks for expanding on that, it's much clearer now. However, is there any reason why it didn't work? It didn't return any errors, and somefile was in the same directory as it, yet it still always returned "Cannot find somefile, quiting..." – Joshua Strot Dec 28 '13 at 02:35
  • Try putting `set -x` at the top of the script. This will make it show each line as it's executing it, with variables expanded. What does it show for the `if` line? – Barmar Dec 28 '13 at 02:40
  • Actually, it looks like it was a problem with the name, the person who wrote it accidentally replaced a period in the somefile name with a comma. – Joshua Strot Dec 28 '13 at 02:50