0

I'm looking to use docker more frequently, and I ended up with a template directory structure a bit like:

My-New-Project/
    |- Dockerfile
    |- build.sh
    |- start.sh
    |- src/...

Where build.sh & start.sh are just the usual docker build -t my-new-project . and docker run -p 8888:8888 -v $(pwd):/workdir my-new-project

However, I need to modify the image name in build.sh & start.sh for every new project - how could I use bash to set the image name based on the directory basename.

Also, if there are best practices against doing what I'm doing please let me know.

Myccha
  • 961
  • 1
  • 11
  • 20
  • I find your approach a bit good, maybe I'll try it. But for now, I use this [approach](https://medium.com/@paulredmond/my-simple-approach-to-using-docker-and-php-b8f6ee76f43c). Concerning your bash question: did you try to explore the **basename** command? – Abel LIFAEFI MBULA Oct 20 '20 at 06:15

1 Answers1

2

Combining the answers from How to set image name in Dockerfile? and Get current directory name (without full path) in a Bash script, all you need to do in your build.sh and start.sh is to:

docker build -t "${PWD##*/}" and docker run -p 8888:888 -v $(pwd):/workdir "${PWD##*/}"

Or, assuming you also need the name to be lowercase as in your example (How to convert a string to lower case in Bash?):

dirname=${PWD##*/}

docker build -t "${dirname,,}"

${PWD##*/} uses shell parameter expansion to remove the other directories from the path, and ,, is another one that converts upper to lowercase.

tripleee
  • 175,061
  • 34
  • 275
  • 318
Teemu Risikko
  • 1,205
  • 11
  • 16
  • 1
    Maybe note that `${dirname,,}` is Bash 4+ only. Poor macOS users are still on Bash 3.x out of the box. The other parameter expansion is compatible with any shell, Bash or POSIX `sh`. – tripleee Oct 20 '20 at 06:45
  • Thank you, this looks great - except I am a poor macOS user - how do you cast to lowercase in bash 3.x? – Myccha Oct 20 '20 at 10:36