If conditional

Hi,

I am new to unix and shell scripting.In my script,there is a line using the "if" conditional -

if [$x != "," ] && [$x != ","]; then
do something

Here "x" is a variable holding string value.If it is not equal to a comma or a string,only then I want to enter the "if" loop. But I am getting error while running this. The error says - " != Expecting unary operator" . Please let me know what is wrong and how to correct it.

You should protect your variables with quotes, and also you need spaces around the [ and ] characters, e.g.

if [ "$x" != "a_string" ] && [ "$x" != "," ]; then
    #do something
fi

Please help me.

Thanks a lot Annihilanic. It is working now.

In addition you should use double brackets:

if [[ "$x" != "a_string" ]] && [[ "$x" != "," ]]; then
    #do something
fi

While the inner closing and opening brackets I marked bold can be left away.

Also you can use the advanced search function of the forum and search thread titles with "if condition" and gets of examples, solutions and further explanations.

Depends on the shell though, if it's plain-old-Bourne-shell or the script needs to be very portable single brackets are still useful...

With that in mind it could also be improved like this:

if [ "$x" != "a_string" -a "$x" != "," ]; then

There is one more question. I have a string(suppose $str). If it starts with a comma(there can be more than one comma at the start),I have to remove all the commas from the beginning.So i have to check if the string starts with a comma.If it does,I have to delete all the commas which are at the start of the string.Please help.

root@isau02:/data/tmp/testfeld> echo ",,,weeeeeekend"| sed 's/^,\+//'
weeeeeekend

Thanks for your reply.But what I need is,I want to delete starting commas from the variable (say $str) and the changes should be made to the original variable so that when I access $str the next time,the starting commas are not there.Please help.

str=",,,weeeeeekend"
str=`echo "${str}"| sed 's/^,\+//'`
echo "${str}"
weeeeeekend

You can use the sed ( stream editor) to do this.. Please see the below example so that you can eliminate the starting commas.

$echo ",,,checking" | sed 's/,/ /g'
$ checking

The output will have spaces in front of "checking". To eliminate the space you have to use.

$echo ",,,checking" | sed 's/,//g'
$checking

$echo ",,,checking," | sed 's/^,*//'
$checking

Now you can verify.

See the below two examples:

e.g.1

$str=",,,checking,"
$echo $str | sed 's/,//g'
$checking

This will eliminate all the commas in the string (before, after & in-between).

e.g.2
$str=",,,checking,"
$echo $str | sed 's/^,*//'
$checking,

To remove the beginning commas use the above sed command (It won't remove commas after the characters) like example2.

Hope this will solve the errors..

Alternatively you can use the simple "tr" command to do this..
for eg :
$str=",,,ch,ecking,"
$echo $str | tr -d ","
O/P --> $checking

Thanks,
Saravana