Monthseptember 2023

Locally remount volumes from Docker to be used by local user using bindfs

#!/bin/bash
set -exou pipefail

# Location of the script (not the location from where it is executed from
THISDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

DOCKER_VOLUME_DIR=volumes  # This is the directory docker mounts to
LOCAL_DOCKER_VOLUME_DIR=localvolumes # This is the directory you want to locally mount to.
INSIDE_CONTAINER_USER=1000

# Bindfs is required
APP=bindfs; [ -x "`which ${APP}`" ] || sudo apt install ${APP}

# Create local directory to map volume to.
[ ! -d ${THISDIR}/${LOCAL_DOCKER_VOLUME_DIR} ] && mkdir -p ${THISDIR}${LOCAL_DOCKER_VOLUME_DIR}

# Unmount if already mounted
sudo umount ${THISDIR}/${LOCAL_DOCKER_VOLUME_DIR} || true

# Bet local users group
GROUP=`id -g -n $USER`

# Mount
sudo bindfs -u $USER -g "$GROUP" --create-for-user=${INSIDE_CONTAINER_USER} --create-for-group=${INSIDE_CONTAINER_USER} ${THISDIR}/${DOCKER_VOLUME_DIR} ${THISDIR}/${LOCAL_DOCKER_VOLUME_DIR}

Based on https://www.fullstaq.com/knowledge-hub/blogs/docker-and-the-host-filesystem-owner-matching-problem

Bash cheatsheet!

Just a collection of oneliners often use, but always forget 🙂 The following can be used from the terminal, or be used as a script.

#!/bin/bash
# ^^ Always start with a shebang!

# -e = immediately exit if any command has non-zero exit status
# -o pipefail = prevents masking of errors in a pipeline
# -u = error when using reference that has not been defined 
set -eou pipefail

# Check if directory is present before creating to avoid annoying warning.
[ ! -d /tmp/whatever ] && mkdir -p /tmp/whatever

# Check if file exists before performing operation on it.
[ -f file.txt ] && echo "blah" >> file.txt

# Check that script is NOT run as root
[[ $EUID -ne 0 ]] || {
    echo "[ERROR]     Do not run as root!"
    exit 1
}

# Check that script is run as root
[[ $EUID -ne 0 ]] && {
    echo "[ERROR]     This script must be run as root"
}

# Location of the script (not the location from where it is executed from
THISDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

# Grep, but do not match grep itself -> put first character of grep match in square brackets []. Suppose we want to see if blender is still running:
ps ax | grep [b]lender

# Kill application by name (when pkill is absent ;) ) Suppose we want to kill "my-awesome-app" 
ps ax | grep -i [m]y-awesome-app | awk '{ print $2 }'

# Install only if not installed.
APP=bindfs; [ -x "`which ${APP}`" ] || sudo apt install ${APP}

# Use default if first argument on command line is not set.
FIRST_ARG="${1:-some_default_var}"  

# Get the amount of CPUs on the device (-1, to use for parallel jobs)
cpus=$(($(nproc) -1))
# Or
cpus=$(($(grep -c "^processor" /proc/cpuinfo) - 1))

© 2025 Roholt

Thema door Anders NorénOmhoog ↑