4 ms·
#!/bin/bash # Grab the container name and use fzf to let us pick it result=$(docker container ls --format "{{.Names}}" | fzf) # No command - try b
by noir_lord 3y ago
#!/bin/bash
# Grab the container name and use fzf to let us pick it
result=$(docker container ls --format "{{.Names}}" | fzf)
# No command - try bash
if [ $# -eq 0 ]
then
echo "docker exec -it $result /bin/bash"
docker exec -it "$result" /bin/bash
fi
# Command was given so use that
if [ $# -eq 1 ]
then
echo "docker exec -it $result $1"
docker exec -it "$result" "$1"
fi
Requires fzf but other wise `ec, select container, it'll try bash or whatever shell/command you supplied.
- mozman 3y agoAlways use [[ and ]] where possible in conditions. You could also use set -x and avoid the echo
- distcs 3y ago[[ and ]] are not portable. [ and ] are portable and specified in POSIX. Like if you always use [[ and ]] you are going to be surprised when the default shell used for running unattended scripts in Debian, Ubuntu refuses to run your script. dash: 1: [[: not found I know your parent commenter mentioned "#!/bin/bash" so your point is still valid. But I recommend that always use "#!/bin/sh" and always use [ and ] so that the scripts are portable. I say this as a former package maintainer who has spent a great deal of time converting Bash scripts to POSIX sh scripts just so that I can package them as .deb.
- hakre 3y agoIMHO this is also a good remark in context of those container images that most of all have /bin/sh. Technically not all, but many distro based containers. so if someone plans to extend the script so that it injects it iself into the container or what not.
- rascul 3y agoI'll take the bash dependency. The features are well worth it.
- svilen_dobrev 3y agosimpler: just this, after the result=.. docker exec -it "$result" "${1:-/bin/bash}"
- xp84 3y agoCan you explain this last part? This is why I usually stop myself from trying anything very complex with shell scripts: unlike scripting languages, half the power of shell is hiding inside little piles of punctuation marks that I don’t think I can even Google!
- noir_lord 3y agoUse the argument ($1) if supplied otherwise default to /bin/bash. It's why I avoid using stuff like that because I won't remember how it works in 6mths.