Frage

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?

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top