27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

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

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

echo "var1 = $var1"<br />

# var1 = first line second line<br />

# For each line terminated by a "\",<br />

# you get a prompt on the next line to continue feeding characters into var1.<br />

echo; echo<br />

echo "Enter another string terminated by a \\ , then press ."<br />

read −r var2 # The −r option causes the "\" to be read literally.<br />

# first line \<br />

echo "var2 = $var2"<br />

# var2 = first line \<br />

# Data entry terminates with the first .<br />

echo<br />

exit 0<br />

The read command has some interesting options that permit echoing a prompt and even reading<br />

keystrokes without hitting ENTER.<br />

# Read a keypress without hitting ENTER.<br />

read −s −n1 −p "Hit a key " keypress<br />

echo; echo "Keypress was "\"$keypress\""."<br />

# −s option means do not echo input.<br />

# −n N option means accept only N characters of input.<br />

# −p option means echo the following prompt before reading input.<br />

# Using these options is tricky, since they need to be in the correct order.<br />

The −n option to read also allows detection of the arrow keys and certain of the other unusual keys.<br />

Example 11−5. Detecting the arrow keys<br />

#!/bin/bash<br />

# arrow−detect.sh: Detects the arrow keys, and a few more.<br />

# Thank you, Sandro Magi, for showing me how.<br />

# −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−<br />

# Character codes generated by the keypresses.<br />

arrowup='\[A'<br />

arrowdown='\[B'<br />

arrowrt='\[C'<br />

arrowleft='\[D'<br />

insert='\[2'<br />

delete='\[3'<br />

# −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−<br />

SUCCESS=0<br />

OTHER=65<br />

echo −n "Press a key... "<br />

Chapter 11. Internal Commands and Builtins 128

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

Saved successfully!

Ooh no, something went wrong!