I’m relative new to Bash and i’m trying to clean things up and have a better folder structure.
I’m currently trying to build a script that have options up and down like the famous command "Docker-Compose Up
" & "Docker-Compose Down
"
My only issue is that i’m not too familiar with If function or if anyother function to make Up and Down as options or arguments
My current scripts is below
compose-up.sh
#!/bin/bash
sudo docker-compose -f /home/home/compose/tools.yml -f /home/home/compose/dashboards.yml up -d
compose-down.sh
#!/bin/bash
sudo docker-compose -f /home/home/compose/tools.yml -f /home/home/compose/dashboards.yml down
The new script should be named compose.sh and i would like if i can just type
./compose.sh up
to run and create those containers in Docker
./compose-sh down
to stop and delete those containers in Docker
MAKING IT DYNAMIC = IDEAL SCRIPT
The biggest design flaw with my code is that its not dynamic. This is probably a more complicated code down the road for improvement but if its easier for someone to create a code to basically run Docker-Compose Up
on all xml files within specific directory such as /home/home/compose
. For example, all xml files within the folder "compose" will be automatically docker-compose up and if i want to do docker-compose down too
2
Answers
SCRIPT
I managed to create a bash code with the assistance of an old friend to make my code dynamic. Enjoy :)
The script provides functions for common Docker Compose commands such as down, up, restart, stop, pull, and start.
The main goal was to able to automate and run docker-compose files based on the current folder of pwd.
The functions correctly find all YAML files in the current directory and use them as input for the Docker Compose commands.
ADD TO PATH
In a shell script, any additional command-line parameters are passed in numbered variables
$1
,$2
, and so on.You have a couple of invocations of
docker-compose
with similar options. I’d wrap these in a shell function. Here"$@"
means "and all of the additional options passed to the function".In the main script, there are a couple of ways to check what the argument is. I might use the shell
case
statement hereIn the
case
statement, there are a series of lines starting with a shell glob and a close parenthesis. If the expression"$1"
matches the pattern, then the command is executed, up to the next;;
.esac
ends the block.Make sure to start the script with a "shebang" line,
#!/bin/sh
on a line on its own, and mark the script executable before you commit it to source control.