24.07.2018 Views

Bash-Beginners-Guide

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

[carol@octarine ~/test] ls -a<br />

./ ../ test test~<br />

The tr is part of the textutils package; it can perform all kinds of character transformations.<br />

9.6. Making menus with the select built-in<br />

9.6.1. General<br />

9.6.1.1. Use of select<br />

The select construct allows easy menu generation. The syntax is quite similar to that of the for loop:<br />

select WORD [in LIST]; do RESPECTIVE-COMMANDS; done<br />

LIST is expanded, generating a list of items. The expansion is printed to standard error; each item is preceded<br />

by a number. If in LIST is not present, the positional parameters are printed, as if in $@ would have been<br />

specified. LIST is only printed once.<br />

Upon printing all the items, the PS3 prompt is printed and one line from standard input is read. If this line<br />

consists of a number corresponding to one of the items, the value of WORD is set to the name of that item. If<br />

the line is empty, the items and the PS3 prompt are displayed again. If an EOF (End Of File) character is<br />

read, the loop exits. Since most users don't have a clue which key combination is used for the EOF sequence,<br />

it is more user-friendly to have a break command as one of the items. Any other value of the read line will set<br />

WORD to be a null string.<br />

The read line is saved in the REPLY variable.<br />

The RESPECTIVE-COMMANDS are executed after each selection until the number representing the break<br />

is read. This exits the loop.<br />

9.6.1.2. Examples<br />

<strong>Bash</strong> <strong>Guide</strong> for <strong>Beginners</strong><br />

This is a very simple example, but as you can see, it is not very user-friendly:<br />

[carol@octarine testdir] cat private.sh<br />

#!/bin/bash<br />

echo "This script can make any of the files in this directory private."<br />

echo "Enter the number of the file you want to protect:"<br />

select FILENAME in *;<br />

do<br />

echo "You picked $FILENAME ($REPLY), it is now only accessible to you."<br />

chmod go-rwx "$FILENAME"<br />

done<br />

[carol@octarine testdir] ./private.sh<br />

This script can make any of the files in this directory private.<br />

Enter the number of the file you want to protect:<br />

1) archive-20030129<br />

2) bash<br />

3) private.sh<br />

#? 1<br />

Chapter 9. Repetitive tasks 117

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!