Skip to content

Instantly share code, notes, and snippets.

@karlkfi
Created February 2, 2021 07:16
Show Gist options
  • Save karlkfi/246d60fda66cbfbb10eca2a7fceefd73 to your computer and use it in GitHub Desktop.
Save karlkfi/246d60fda66cbfbb10eca2a7fceefd73 to your computer and use it in GitHub Desktop.
bash2asciicast.sh - Convert a bash script into an asciinema recording
#!/usr/bin/env bash
# Convert a bash script into an asciinema recording
set -o errexit -o nounset -o pipefail
INPUT_FILE=${1:-}
if [[ -z "${INPUT_FILE}" ]]; then
echo "Syntax: $0 <path/to/bash-scipt.sh> <path/to/out.cast>"
exit 1
fi
OUTPUT_FILE=${2:-}
if [[ -z "${OUTPUT_FILE}" ]]; then
echo "Syntax: $0 <path/to/bash-scipt.sh> <path/to/out.cast>"
exit 1
fi
CHAR_STEP=0.05
LINE_STEP=0.5
IFS='' read -r -d '' BG_SCRIPT << EOF || true
set -o errexit -o nounset -o pipefail
sleep 1
while IFS="" read -r line; do
if [[ "\${line}" == "#!"* ]]; then
# skip shebang
continue
fi
# loop utf-8 characters and print them individually
while IFS="" read -r char; do
echo -n "\${char}"
sleep ${CHAR_STEP}
done <<< "\$(echo "\${line}" | sed -e 's/\(.\)/\1\n/g')"
echo
sleep ${LINE_STEP}
done < "/dev/stdin"
echo
echo "exit"
EOF
cat "${INPUT_FILE}" | bash -c "${BG_SCRIPT}" | asciinema rec --stdin "${OUTPUT_FILE}"
@karlkfi
Copy link
Author

karlkfi commented Feb 2, 2021

Note: There's no backpressure from asciinema to wait fo commands to complete, so if you have long commands, you may want to add a longer sleep to replace the sleep ${LINE_STEP}.

For example:

  if [[ "\${line}" == "kpt pkg get "* ]]; then
    sleep 10.0
  elif [[ "\${line}" == "kpt cfg set "* ]]; then
    sleep 2.0
  elif [[ "\${line}" == "kubectl "* ]]; then
    sleep 10.0
  else
    sleep ${LINE_SLEEP}
  fi

This will of course create long pauses in the recording, but you can work around that by adding -i 2 to the asciinema command, which will shorten idle pauses to a max of 2 seconds in the output recording.

The only other solution I could come up with would be to write the asciicast manually, as in https://gist.github.com/karlkfi/3e286f507c2d0ae7f8a1994e4e137a7e

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment