0

Goal: less the contents (from a variable) and then ask the user whether the contents should be saved to a file (i.e., .recovered_object) only after the user quits out of less.

The excerpt from my script is reproduced below:

...
    # Show each blob until one is chosen
    counter=1
    while IFS='' read sha; do
        printf "Showing blob %d of %d" "$counter" "$BLOB_COUNT"
        contents=$(git show ${sha})
        ${PAGER:-less} ${contents}
        if read -q '?Save and quit (y/n) ?'; then
            echo "$contents" > .recovered_object
            exit 0
        else
            ((counter++))
        fi
    done <<< ${DANGLING_BLOBS_SHA}

    exit 0

As it stands now, any keypress (other than y) skips to the next file...but this precludes the user from scrolling up (k) or down (j) or using less's other keymappings!

How do I prevent the if block from immediately running?


PS: I'm pretty new to shell scripting in general, so any pointers are welcome.

PSS: I am using zsh, but am not opposed to switching to bash if that's more conducive to achieving the desired UX.

2
  • I see a number of problems here: less expects a filename as an argument, not a bunch of data (also, the variable isn't quoted, so it'll go through word splitting and wildcard expansion anyway). Since input to the loop is redirected (with <<<), read is going to read from that instead of the terminal. Also, echo ... > .recovered_object will overwrite any previous contents, so you'll only get the last saved blob (the previous ones have been overwritten). Commented Mar 1, 2021 at 3:30
  • For my purposes, I want to keep the here-string and I only want the latest chosen contents saved to .recovered_object. Thanks for catching the quotation issue. Commented Mar 1, 2021 at 3:40

1 Answer 1

0

Using process substitution with the -f flag (also --force) seemed to work:

${PAGER:-less} -f <(echo "$contents")

2
  • 1
    Why not just echo "$contents" | "${PAGER:-less}", instead of relying on a less-specific -f? Commented Mar 1, 2021 at 4:03
  • Ooof. Yes, that's far more sensible. Thanks. Commented Mar 1, 2021 at 4:07

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.