Home > front end >  How to get script directory (not current directory) in shell (sh) script (not bash)?
How to get script directory (not current directory) in shell (sh) script (not bash)?

Time:06-17

Folder structure:

#root
|- deployment
|  |- start-dev.sh
|  |- docker-compose.yml
|  |- // other files including app.Dockerfile and anything else I need
|- // everything else

Initial start-dev.sh

#!/bin/sh

docker-compose -p my-container up -d
docker-compose -p my-container exec app bash

Working state

In VS Code (opened as WSL2 remote) integrated terminal I would type

cd deployment
./start-dev.sh

and deployment is successful.

If instead, I tried just deployment/start-dev.sh it fails, since there's no docker-compose.yml in the current directory.

Desire

I want

deployment/start-dev.sh

to work.

Solution 1 for start-dev.sh

#!/bin/bash

BASEDIR=$(dirname $0)

docker-compose -f "${BASEDIR}/docker-compose.yml" -p my-container up -d
docker-compose -f "${BASEDIR}/docker-compose.yml" -p my-container exec app bash

Question

How do I convert Solution 1 to be a sh script instead of bash?

CodePudding user response:

Solution 2

#!/bin/sh

a="/$0"; a=${a%/*}; a=${a#/}; a=${a:-.}; BASEDIR=$(cd "$a"; pwd)

docker-compose -f "${BASEDIR}/docker-compose.yml" -p my-container up -d
docker-compose -f "${BASEDIR}/docker-compose.yml" -p my-container exec app bash

CodePudding user response:

Change the very first line of the script to use #!/bin/sh as the interpreter. You don't need to change anything else.

In particular, the POSIX.1 specification includes dirname and $(command) substitution, so you're not using anything that's not a POSIX shell feature. I'd expect this script to work in minimal but standard-conforming shells like BusyBox's, and so in turn to work in any Docker image that includes a shell.

There are other recipes too, though they do typically rely on dirname(1). See for example How can I set the current working directory to the directory of the script in Bash?, which includes non-bash-specific answers.

  • Related