Last active
March 13, 2022 11:33
-
-
Save nat-418/b482646f7bbe0cfaed2bca8b98a3c701 to your computer and use it in GitHub Desktop.
How to prompt user input from an interactive text editor in POSIX shell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# | |
# How to prompt user input from an interactive text editor in POSIX shell. | |
# ====================================================================== | |
# | |
# Permission to use, copy, modify, and/or distribute this software for any | |
# purpose with or without fee is hereby granted. | |
# | |
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH | |
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY | |
# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, | |
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM | |
# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR | |
# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR | |
# PERFORMANCE OF THIS SOFTWARE. | |
# | |
# Create a temporary file using only POSIX commands | |
# ------------------------------------------------- | |
umask 0177 | |
tempfile=/tmp/"$0"."$$"."$(awk 'BEGIN {srand();printf "%d\n", rand() * 10^10}')" | |
trap 'rm -f -- "$tempfile"' INT TERM HUP EXIT | |
: > "$tempfile" | |
# Editor to use, set to vi if not specifed in the environment | |
# ----------------------------------------------------------- | |
: "${EDITOR:=vi}" | |
# Open the input file for editing | |
# ------------------------------- | |
$EDITOR "$tempfile" | |
# Read the file into a variable | |
# ----------------------------- | |
user_input="$(cat "$tempfile")" | |
# Use the input | |
# ------------- | |
printf "User input:\n%s\n" "$user_input" | |
# Cleanup | |
# ------- | |
rm "$tempfile" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment