0

When I run sh ./mypath/myscript.sh with the code below,

BASEDIR=$(dirname "$0")
echo "$BASEDIR"

I got ./mypath which is great.

However, since I need to source due to -bash: [: =: unary operator expected. when no parameter given,

The above code doesn't work, but just return -bash instead. Is there an equivalent of the above code that work when source instead of sh?

Community
  • 1
  • 1
Elye
  • 53,639
  • 54
  • 212
  • 474
  • This is [BashFAQ #28](http://mywiki.wooledge.org/BashFAQ/028). – Charles Duffy Mar 08 '17 at 04:37
  • 1
    and btw, `sh` isn't bash; if you run `sh yourscript`, then the only capabilities guaranteed to be present are those specified in the POSIX sh standard. Even if your system's POSIX sh interpreter *is* bash, it runs in a barebones compatibility mode with lots of features turned off when invoked that way. Always use `bash yourscript`, or a `#!/bin/bash` shebang, to ensure that full functionality is available. – Charles Duffy Mar 08 '17 at 04:37
  • 1
    Cool. The answer to my inquiry is `DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"` – Elye Mar 08 '17 at 04:42
  • 1
    In most circumstances, `dir=${BASH_SOURCE%/*}` will suffice without the other fanciness. (Aside: All-caps variable names are reserved for use by variables with meaning to the operating system or shell; using lowercase names for your own variables avoids overwriting meaningful ones by accident. See relevant POSIX spec at http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html, paragraph 4, keeping in mind that setting a shell variable with a name matching any preexisting environment variable will overwrite the latter). – Charles Duffy Mar 08 '17 at 04:54

0 Answers0