3 ms·
Using raw escape codes is ugly and device-dependent. People learned this in the 1970’s, and created libraries to get away from having to hard-code escape codes
by teddyh 5y ago
Using raw escape codes is ugly and device-dependent. People learned this in the 1970’s, and created libraries to get away from having to hard-code escape codes.
Here’s a device-independent variant:
title(){ tput tsl || tput -T xterm+sl tsl; printf %s "$*"; tput fsl || tput -T xterm+sl fsl; }
Note: if the terminal does not advertise support of the necessary capabilities, it falls back to using the XTerm escape sequences.
- mdaniel 5y agoAs a point of comparison, I ssh-ed into my mac and ran "tput -T xterm+sl tsl" in order to see what it would output, and it hung my connection So, I'll stick to my printf thanks
- teddyh 5y agoYou can’t run only one of the tput commands! You need to run both of them, as in the shell function; i.e. both tsl and fsl needs to be sent to the terminal! If you want to see what bytes it would output, use “od”: tput -T xterm+sl tsl | od -t c
- mdaniel 5y agoYeah, I actually thought about that afterward, however, in that same "I wonder what happened", I also wondered if tput is bright enough to know the difference between the local termcap and the connected one As a concrete example, my printf version works even when run inside docker, but $ docker run --rm ubuntu:22.04 bash -c '{ tput tsl || tput -T xterm+sl tsl; } | od -c' tput: No value for $TERM and no -T specified tput: unknown terminal "xterm+sl" 0000000
- teddyh 5y agoYour example suffers from being a toy example; it makes no sense to run a noninteractive command in a docker container merely to output terminal escape codes. If this were the norm, "docker run” would probably by default make sure to copy the TERM setting to the inner command. I would assume that if you run an interactive shell inside docker, TERM would actually be set correctly. It’s the same when you ssh somewhere else – the TERM environment variable is sent along, so that the remote program can see it and output the correct codes for your local terminal. Also, the docker image needs the terminfo database installed for “tput” to work.
- mdaniel 5y agoHaving arrived back at my Mac, running iTerm2, I wanted to share another fun fact about using those executables: running that function while the outer shell is in "set -x" causes the title of the window to be + printf %s 'hello world'^M^Jhello world+ tput fsl^M^J+tput -T xterm and that's where it cuts off but I presume ends with "^M^J" at the end :-D