File: lxc-login.sh
   1 #!/bin/sh
   2 
   3 # The MIT License (MIT)
   4 #
   5 # Copyright (c) 2026 pacman64
   6 #
   7 # Permission is hereby granted, free of charge, to any person obtaining a copy
   8 # of this software and associated documentation files (the "Software"), to deal
   9 # in the Software without restriction, including without limitation the rights
  10 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11 # copies of the Software, and to permit persons to whom the Software is
  12 # furnished to do so, subject to the following conditions:
  13 #
  14 # The above copyright notice and this permission notice shall be included in
  15 # all copies or substantial portions of the Software.
  16 #
  17 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23 # SOFTWARE.
  24 
  25 
  26 # lxc-login [container]
  27 #
  28 # Start the LXC container given and attach into its running LOGIN shell.
  29 #
  30 # The shell is attached using a `clean` environment, to avoid leaking
  31 # many details via environment variables.
  32 
  33 
  34 case "$1" in
  35     -h|--h|-help|--help)
  36         awk '/^# +lxc-login /, /^$/ { gsub(/^# ?/, ""); print }' "$0"
  37         exit 0
  38     ;;
  39 
  40     -n|--name)
  41         if [ $# -lt 2 ]; then
  42             printf "forgot the container name\n" >&2
  43             exit 1
  44         fi
  45         shift
  46     ;;
  47 esac
  48 
  49 [ "$1" = '--' ] && shift
  50 
  51 container="$1"
  52 if [ $# -eq 0 ] && command -v fzf > /dev/null; then
  53     container="$(lxc-ls -1 | fzf --reverse --height 50% --tmux 50%)"
  54     if [ -z "${container}" ]; then
  55         awk '/^# +lxc-login /, /^$/ { gsub(/^# ?/, ""); print }' "$0"
  56         exit 1
  57     fi
  58 fi
  59 
  60 if [ -z "${container}" ]; then
  61     awk '/^# +lxc-login /, /^$/ { gsub(/^# ?/, ""); print }' "$0"
  62     exit 1
  63 fi
  64 
  65 lxc-start "${container}" 2> /dev/null
  66 
  67 printf "\n\e[7mentered\e[0m shell from LXC container \e[7m%s\e[0m\n\n" \
  68     "${container}" >&2
  69 
  70 lxc-attach \
  71     --clear-env \
  72     --set-var "LXC_CONTAINER_NAME=${container}" \
  73     --set-var "TERM=${TERM:-xterm}" \
  74     "${container}"
  75 res=$?
  76 
  77 printf "\n\e[7mexited\e[0m shell from LXC container \e[7m%s\e[0m\n\n" \
  78     "${container}" >&2
  79 
  80 exit "${res}"