UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 45.34 Arrays in the Bourne Shell Chapter 45
Shell Programming for the Initiated
Next: 45.36 Shell Lockfile
 

45.35 Using a Control Character in a Script

There are times when you need to use non-printing control characters in a script file. If you type them directly into the file, they can be invisible to printers and on your screen - or, worse, they can cause trouble when you print or display the file.

One time you might need to store control characters in a script is when you're writing sed substitution commands; you don't know what delimiters to use because the strings you're substituting could contain almost any text:

sed "s/$something/$whoknows/"

Because sed can use almost any character as the delimiter (34.7), you can use a control character like CTRL-a instead of the slash (/). Another time you might also need to use non-printable strings of characters is for controlling a terminal; you won't want to type an Escape character directly into the file.

The answer is to use a command that will create the control characters as the script runs - and store them in shell variables.

45.35.1 With echo

If your version of echo (8.6, 46.10) interprets an octal number in a string like \001 as its ASCII value (51.3), the job is easy. An octal-to-ASCII chart shows you that 001 is CTRL-a. You can store the output of echo in a shell variable, and use the variable wherever you need a CTRL-a character:

`...` 

ca=`echo '\001'`     # control-A character
   ...
sed "s${ca}$something${ca}$whoknows${ca}"

45.35.2 With tr and echo

If your echo can't make control characters directly, the tr utility can do it for you. tr understands octal sequences, too. Make your echo output characters you don't want, and have tr translate them into the control characters you do want. For example, to make the 4-character sequence ESCape CTRL-a [ CTRL-w, use a command like this:

escseq=`echo 'ea[w' | tr 'eaw' '\033\001\027'`

tr reads the four characters down the pipe from echo; it translates the e into ESCape (octal 033), the a into CTRL-a (octal 001), and the w into CTRL-w (octal 027). The left bracket isn't changed; tr prints it as is.

The script.tidy script in article 51.6 shows a way to set several control characters in several shell variables with one command - that's efficient because it cuts the number of subprocesses needed. Another way to get control characters is with the handy jot (45.11) command on the CD-ROM.

- JP


Previous: 45.34 Arrays in the Bourne Shell UNIX Power ToolsNext: 45.36 Shell Lockfile
45.34 Arrays in the Bourne Shell Book Index45.36 Shell Lockfile

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System