Bash scripting missing ']'

BashScripting

Bash Problem Overview


I am getting an error ./test.sh: line 13: [: missing `]' in the file test.sh I tried using brackets and other options such as -a or by checking the size of the file p1 but the error is always there and the else statement is always executed irrespective of the input given.I even tried by removing the ; in line 13 but it didn't help.

test.sh

#!/bin/bash
echo "Enter app name"
read y
$y &
top -b -n 1 > topLog.log
#-w checks for the whole word not and sub string from that word
grep -w "$y" topLog.log > p1
#-s option checks if the file p1 is present or not
if [ -s "p1"];  #line 13
then 
    echo "Successful "
else
    echo "Unsuccessful"
fi
rm p1

I am new to bash scripting.So if there is any silly mistake please excuse me.

Bash Solutions


Solution 1 - Bash

Change

if [ -s "p1"];  #line 13

into

if [ -s "p1" ];  #line 13

note the space.

Solution 2 - Bash

I got this error while trying to use the && operator inside single brackets like [ ... && ... ]. I had to switch to [[ ... && ... ]].

Solution 3 - Bash

You're missing a space after "p1":

if [ -s "p1" ];

Solution 4 - Bash

add a space before the close bracket

Solution 5 - Bash

If you created your script on windows and want to run it on linux machine, and you're sure there is no mistake in your code, install dos2unix on linux machine and run dos2unix yourscript.sh. Then, run the script.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionquick-View Question on Stackoverflow
Solution 1 - BashFredrik PihlView Answer on Stackoverflow
Solution 2 - BashCarl GView Answer on Stackoverflow
Solution 3 - BashElmar PeiseView Answer on Stackoverflow
Solution 4 - BashSam RubyView Answer on Stackoverflow
Solution 5 - BashVladimir MartonView Answer on Stackoverflow