1748170 Members
3979 Online
108758 Solutions
New Discussion юеВ

about shell

 
kamal_15
Regular Advisor

about shell

hi all

i have a lettel question

when i type :
*****************
x="any string"
echo $x
the response is
any string
*****************
if i want to add spaces in variable as follow:
x=" any string"
echo $x
the response is the same
any string
******************

i want the response to be:
(spaces)any string

thank u



kamal


5 REPLIES 5
RAC_1
Honored Contributor

Re: about shell

x="\000 any string"
echo $x

man ascii and man echo for details.
\000 is octal representation of space

Anil
There is no substitute to HARDWORK
Sanjay_6
Honored Contributor

Re: about shell

Hi Kamal,

Try,

x=" any string"
echo "$x"

Hope this helps.

Regds


kamal_15
Regular Advisor

Re: about shell

thank u

i tryed \000
and it works good


thankx
Stuart Abramson
Trusted Contributor

Re: about shell

Sanjay has the simpler answer.

When you type:

x="^any string" (where "^" is a space...)
echo^$x

it expands into:

echo^^any string

Because any number of blanks is a legal seperator, you get "any string".

When you type:

x="^any string" (where "^" is a space...)
echo^"$x"

the space in "$x" is seperated from the word previous space, and will appear in the echo.
Bill Hassell
Honored Contributor

Re: about shell

The key is in the way the shell handles words. When you echo something without quotes, imbedded or leading spaces are treated as item separators and reduced to just 1. If you echo a variable with double quotes, then the entire content of the variable is treated as a single string. This short script shows the difference when you list something line by line. It uses the typeset command to create a right-justified variable filled with spaces, then echoes the variable without quotes and with quotes. NOTE: the ITRC text handler always reduces multiple spaces to 1 so I have changed the space in this example to ^ for visibility:

$ typeset -R10 X=abc
$ echo $X
abc
$ echo "$X"
^^^^^^^abc

When dealing with strings in shells, you are caught between the shell's parsing features and maintaining the integrity of a string.


Bill Hassell, sysadmin