linux像vim、man、less、top一样在终端的新屏幕中输出,退出后清屏返回原屏幕

centos,终端中调用脚本

编写脚本test.sh

#!/bin/bash

#tput smcup
echo -e '\E7'
echo -e '\033[?47h'

tput cup 0 0

echo "aaaaaaaaaaaaa"
echo "aaaaaaaaaaaaa"
echo "aaaaaaaaaaaaa"

sleep 2
tput cup 5 10

echo "dddddddddddddd"
echo "bbbbbbbbbbbbbb"
echo "cccccccccccccc"

sleep 2

#echo -e '\E[2J'
#echo -e '\033[?47l'
#echo -e '\E8'
tput rmcup

tput smcuptput rmcup是进入altscreen和退出altscreen,进入altscreen后相当于开启一个新的虚拟终端,此终端默认占一屏,没有滚动条,
altscreen默认从下往上推动输出,即输出顺序不变,相对位置不变,但是不是从顶部开始输出,而是从底部网上推,所以需要调用tput cup命令设置cursor position(y,x),先竖直距离坐标,再横向距离坐标

smcup、rmcup与echo -e对比:

smcup
\E7 saves the cursor's position
\E[?47h switches to the alternate screen
rmcup
\E[2J clears the screen (assumed to be the alternate screen)
\E[?47l switches back to the normal screen
\E8 restores the cursor's position.

详见tput命令

参考https://invisible-island.net/xterm/xterm.faq.html#xterm_tite

程序中可以采用ncurses库

main.c

#include <ncurses.h>
#include <unistd.h>

#define DELAY 30000

int main(int argc, char *argv[])
{
	int x = 0;
	int y = 0;
	int max_x = 0,max_y = 0;
	int next_x = 0;
	int direction = 1;
	
	initscr(); /* 初始化屏幕 */
	
	noecho(); /* 屏幕上不返回任何按键 */
	
	curs_set(FALSE); /* 不显示光标 */
		
	/* getmaxyx(stdscr, max_y, max_x);/* 获取屏幕尺寸 */ 

	mvprintw(5, 5, "Hello, world!");
	
	refresh(); /* 更新显示器 */
	
	sleep(1);
	
	while(1)
	{
		getmaxyx(stdscr, max_y, max_x);/* 获取屏幕尺寸 */
		clear(); /* 清屏 */
		mvprintw(y, x, "x");
		refresh();
		
		usleep(DELAY);
		
		next_x = x + direction; 
		
		if(next_x >= max_x || next_x < 0)
		{
			direction = (-1) * direction;
		}
		else
		{
			x = x + direction;
		}
	}
	endwin();  /* 恢复终端 */
}

Makefile:

# Makefile
cc=gcc

LDFLAGS=-lncurses

SRCS := $(wildcard *.c)
TARGET := $(SRCS:%.c=%)

$(TARGET):$(SRCS)
	$(cc) $(LDFLAGS) $(SRCS) -o $(TARGET) 

clean:
	rm $(TARGET)

编译运行后,可以看到hello, world然后消失,一个x在第一行左右移动,ctrl+c可以退出,然后恢复终端

参考

C语言

https://invisible-island.net/ncurses/ncurses-intro.html

shell脚本

https://www.ibm.com/developerworks/cn/aix/library/au-shellcurses/index.html

python

https://docs.python.org/3/howto/curses.html

小贴士:

查看vim依赖库

ldd /bin/vim

查看vim中的符号

nm /bin/vim
nm: /bin/vim: no symbols

如果普通程序没有符号输出,加上-D参数

nm -D /bin/vim

发布了275 篇原创文章 · 获赞 46 · 访问量 28万+

猜你喜欢

转载自blog.csdn.net/youyudexiaowangzi/article/details/97763505