The FreeBSD Diary

The FreeBSD Diary (TM)

Providing practical examples since 1998

If you buy from Amazon USA, please support us by using this link.
[ HOME | TOPICS | INDEX | WEB RESOURCES | BOOKS | CONTRIBUTE | SEARCH | FEEDBACK | FAQ | FORUMS ]
Scripts / handy tips
 New Topic  |  Go to Top  |  Go to Topic  |  Search  |  Log In   Previous Message  |  Next Message 
 shell eating $
Author: Dan 
Date:   18-01-10 00:55

Tonight I was trying to do a very simple task. This simple shell script demonstrates it:

#!/bin/sh

loaded="Data Transfer Element 0:Full (Storage Element 2 Loaded):VolumeTag = DGG440"

echo "loaded='${loaded}'"
echo "${loaded}" | awk "{print \$7}"

echo before
slot=`echo "${loaded}" | awk "{print \$7}"`
echo after

echo "slot='${slot}'"



The output is:


# sh test.sh
loaded='Data Transfer Element 0:Full (Storage Element 2 Loaded):VolumeTag = DGG440'
2
before
after
slot='Data Transfer Element 0:Full (Storage Element 2 Loaded):VolumeTag = DGG440'


But what I want is

slot='2'

The problem: unescaped $

This demonstrates the problem:


# sh -x test.sh
+ loaded='Data Transfer Element 0:Full (Storage Element 2 Loaded):VolumeTag = DGG440'
+ echo 'loaded='\''Data Transfer Element 0:Full (Storage Element 2 Loaded):VolumeTag = DGG440'\'
loaded='Data Transfer Element 0:Full (Storage Element 2 Loaded):VolumeTag = DGG440'
+ echo 'Data Transfer Element 0:Full (Storage Element 2 Loaded):VolumeTag = DGG440'
+ awk '{print $7}'
2
+ echo before
before
+ + awk '{print }'
echo 'Data Transfer Element 0:Full (Storage Element 2 Loaded):VolumeTag = DGG440'
+ slot='Data Transfer Element 0:Full (Storage Element 2 Loaded):VolumeTag = DGG440'
+ echo after
after
+ echo 'slot='\''Data Transfer Element 0:Full (Storage Element 2 Loaded):VolumeTag = DGG440'\'
slot='Data Transfer Element 0:Full (Storage Element 2 Loaded):VolumeTag = DGG440'


The solution, add an extra $:

slot=`echo "${loaded}" | awk "{print \\$7}"`

Which gives me:

# sh test.sh
loaded='Data Transfer Element 0:Full (Storage Element 2 Loaded):VolumeTag = DGG440'
2
before
after
slot='2'


Great!

Thanks to Josh Paetzel

--
Webmaster

 Reply To This Message  |  Forum List  |  Flat View   Newer Topic  |  Older Topic 

 Topics Author  Date
 shell eating $   new
Dan 18-01-10 00:55 
 Re: shell eating $   new
Chris Elvidge 19-08-10 08:54 


 Forum List  |  Need a Login? Register Here 
 User Login
 User Name:
 Password:
 Remember my login:
   
 Forgot Your Password?
Enter your email address or user name below and a new password will be sent to the email address associated with your profile.
How to get the most out of the forum

phorum.org