[TAG] need some help
Ben Okopnik
ben at linuxgazette.net
Wed Jul 11 19:49:04 MSD 2007
On Tue, Jul 10, 2007 at 12:34:05PM +0530, Nayanam,Sarsij wrote:
> I am writing a shell script to run on MC/SG cluster , and I am facing an
> issue as mentioned below:
>
> if we have a package with a dash in the name say sgpkg-cust :
>
> # PKGsgpkg-cust=hello
> sh: PKGsgpkg-cust=hello: not found.
> # PKGsgpkg=hello
> # echo $PKGsgpkg-cust
> hello-cust
This is not surprising; a dash is not a valid character in a variable
for Bourne-derived shells.
> I have a function get_package_fqdn which starts as below:
>
> 37 get_package_fqdn()
> 38 {
> 39 eval var=$`echo PKG$1`
> 40 if [[ -z $var ]]; then
> [...]
> 64 fi
> 65 }
>
> we will notice that if $1=sgpkg-cust, var will be equal to "-cust" and the
> rest of the funcion "if[[ -z $var ]];" will not be used and nothing will
> be introduced in the PKG$packagename variable.
This isn't shell-specific, but an excellent Perl programmer named
Mark-Jason Dominus has a writeup called "Why it's stupid to use a
variable as a variable name" (http://perl.plover.com/varvarname.html).
The above problem is explicitly cited. In short: since variable names
are restricted to a specific set of characters, and the set of
characters that could be contained in your '$1' is essentially
arbitrary, you're creating a problem when you do that. So don't do that.
In Perl, the answer is "use a hash". In Bash, well, you need to rethink
what it is that you're trying to do and use different functionality. As
a general approach, you could try "flattening" that arbitrary character
set - be sure to do do in both populating _and_ reading the strings:
```
package_name=$(echo -n "PKG$1"|tr -c 'a-zA-Z0-9_' '_')
'''
``
ben at Tyr:~$ var=$(echo -n "xyzabc@$%^&*()_++sadbjkfjdf" | tr -c 'a-zA-Z0-9_' '_')
ben at Tyr:~$ echo $var
xyzabc____________sadbjkfjdf
''
Do note that this will _still_ break if a "special" Bash character
(e.g., '!') appears in the string. Overall, you just need to rethink
your approach to this problem. MJD is right: it's a bad idea to use a
variable as a variable name.
--
* Ben Okopnik * Editor-in-Chief, Linux Gazette * http://LinuxGazette.NET *
More information about the TAG
mailing list