0

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.

4
  • You need to put spaces between [ and the rest of the things in the if. Commented Oct 7, 2014 at 23:08
  • Gah! I could have sworn I had tried that at least once before! Well that's all it was, thank you! Commented Oct 7, 2014 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). Commented Oct 7, 2014 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[@]} ) Commented Oct 7, 2014 at 23:44

1 Answer 1

1

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]}" ]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.