Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Alright, this is a really simple little thing but it's gotten to the point where I've exhausted 2-3 hours trying to find out why this isn't working and have gotten nowhere.

I'm trying to make Bash/Shell-Script program, and at one point in it, I want to check the contents of an array of strings to see if the string is blank. My code is as follows:

#Display any words the user corrected, and what he/she corrected it with (ignore blank corrections)
printf "\n\n" "MISPELLED  /  CORRECTIONS"
for (( i=0; i<${#words[*]}; i++)); do
if [!"${corrections[$i]}"=""]; then    //this is line 25
   printf "\n ${words[$i]}   ${corrections[$i]}"
fi
done

I'm not positive if the way I used the ! operator was legal, but with or without it, I get the run-time error:

./test: line 25: [=]: command not found

I can post the rest of the code if need be, though I'm mostly confident that the "corrections" array is properly filled with strings.

share|improve this question
    
You need to put spaces between [ and the rest of the things in the if. –  Tom Fenech Oct 7 '14 at 23:08
    
Gah! I could have sworn I had tried that at least once before! Well that's all it was, thank you! –  aredscout Oct 7 '14 at 23:14
    
It is better to use -z for checking if empty or -n for non-empty. if [ -z "${corrections[$i]}" ] will be true if string is empty (blank). if [ -n "${connections[$i]}" ] will be true if string is not empty (not blank). –  alvits Oct 7 '14 at 23:17
    
if your array elements doesn't contains spaces, e.g. each element is one word, you can remove empty elements with arr2=( ${arr1[@]} ) –  jm666 Oct 7 '14 at 23:44

1 Answer 1

up vote 0 down vote accepted

In the shell, [ is a command, so it is important to leave spaces before and after it. On top of that, if you want to check that a string is not empty, you can use -n:

if [ -n "${corrections[$i]}" ]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.