skip to Main Content

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.

Non-solution

The following fails since dirname is not available in my case.

#!/bin/sh

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

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, if dirname is not available in sh?

2

Answers


  1. Chosen as BEST ANSWER

    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
    

  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search