LXF#126 Shell scripting explanation

Code junkies hangout here

Moderators: ChrisThornett, LXF moderators

LXF#126 Shell scripting explanation

Postby Red Bow Tie » Mon Mar 07, 2011 12:14 am

Trying to follow the script Bob Moss has on pg 48-51. Just a beginner so please have patience. When I get to point
echo $var

and then type

sh script_tutorial.sh ''Hello,World\!''

I must assume that the quotes here are two single quotes at the beginning of the Hello,World string and at the end of the line. If I try double quotes here I get


and on the next step, sending the value of the argument ($1) to the file sample.txt results in a blank file.
It does work with two single quotes, though. Is this correct? Why is it necessary to escape the ! mark :?:
Red Bow Tie
Posts: 4
Joined: Sun Mar 06, 2011 11:20 pm

Postby kvonh » Wed Mar 09, 2011 11:20 am

Quoting is a bit of a dark art ... but persist and you will quickly become the expert ...

"double quotes" allow certain things within the quoted string to be be expanded. The best example is shell variables, so for example if you do something like this:

echo "Hello $NAME"

You'll get

Hello Red

'Single quotes' however, cause (almost) everything to be passed through unchanged. Thus:

echo 'Hello $NAME'

will print

Hello $NAME

Now, to answer your question ... The ! character is used by the shell to reference back to previously executed commands. If you type


into the shell, you'll see a numbered list of commands that you have previously entered. If you type at the command prompt:


It will rerun command number 123 from your history. Similarly, if you type


It will rerun the most-recently-entered command that starts with the string foo.

When you use '!' in single quotes, it's special meaning is lost, it just goes through unchanged. Similarly the \ before it: that is passed unchanged, so

echo '\!'

just prints


Now if you use "double quotes" in the same example, it does this (because the \ hides the ! from the shell, conceptually):

echo "\!"

But here's the punchline (note, there is no \backslash here):

echo "!"

fails because the shell cannot find an event in your history to match the !

So, in summary: Bob added a backslash to remove the meaning of the ! He would perhaps have done better to use single quotes (and no backslash).

But that could have caused problems in his script, because in certain cases the shell will *reinterpret* values. The best/safest bet (imho) is to wrap every reference to a variable in "double quotes", thus from Bob's script:

echo "$var"

followed by:

sh script_tutorial 'Hello, World!'

This should Just Work

I hope this helps.

User avatar
Posts: 19
Joined: Tue Apr 12, 2005 9:46 pm

Return to Programming

Who is online

Users browsing this forum: No registered users and 0 guests