7

I have a bash script.sh. I can easily scroll the output like this:

$ ./script.sh | less

But how do I make the output display scrollable automatically, without having to pipe it through less? In other words, how do I put that functionality right into the script itself? I just want to execute the script like this:

$ ./script.sh

I know I might be able to write a different script to execute the first one and pipe the output automatically but I don't want to have to write another script just to get the first one to do what I want it to do. Know what I mean?

3 Answers 3

8

You can write your script like this:

#!/bin/bash
(

    Your script here

) | less
exit $PIPESTATUS 

This will pipe the script output through less if output is a terminal (so you can ./script.sh > file without paging), and it preserves the script's exit code.

Sign up to request clarification or add additional context in comments.

2 Comments

less detects itself redirecting to file and stops paging. (at least on my system). Youre right with the exit code... ;)
It checked whether stdout was a terminal, but as @jm666 points out, less handles that well by itself.
4

Usually enough add the next into your script

#!/bin/bash

(  # add this to the start

#your old script here
date
cat /etc/passwd
df
ls -l
#end of your script

) | less      #and add this to the end

or you can put the whole script into a bash function like

#!/bin/bash

the_runner() {
#your old script here
date
cat /etc/passwd
df
ls -l
#end of your script
}
the_runner "$@" | less

Comments

0

Instead of modifying the script itself I decided to add a special binding to Bash.

Effectively, you'll be able to write ./script.sh instead of ( ./script.sh ) | more.

Here's what you need to add to your .bashrc:

# Switch to vi mode (default is emacs mode).
set -o vi 
dont_scroll_down() {
    # Add the command to your history.
    history -s "$READLINE_LINE"
    # Redirect all output to less.
    bash -c "$READLINE_LINE" 2>&1 | less -eFXR
    # Remove the command from the prompt.
    READLINE_LINE=''
    # Optionally, you can call 'set -o vi' again here to enter
    # insert mode instead of normal mode after returning from 'less'.
    # set -o vi
}
bind -m vi -x '"J": "dont_scroll_down"'

As a result you'll be able to do the following thing:

  1. Type in the command you want to run.

    $ ./script.sh 
    
  2. Hit Escape to exit insert mode and enter normal mode.

  3. Now hit Shift-j to execute the line.

Now you should be able to scroll the output starting from the beginning.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.