Matam Matam - 6 months ago 38
Bash Question

command not found error when redirecting input

I wrote a shell script to be ran on a text file (called test.txt). This script will read an input file, iterate over its lines, and do some action.


I first compile my program:

chmod +x ./cleanLines.txt


then run my command:

./cleanLines.txt < ./test.txt > output.txt


However, the error I get is:

./cleanLines.txt: line 7: [[: command not found
./cleanLines.txt: line 7: [[#Some: command not found
./cleanLines.txt: line 7: [[HelloWorld: command not found
./cleanLines.txt: line 7: [[Today: command not found
./cleanLines.txt: line 7: [[Cookie: command not found
./cleanLines.txt: line 7: [[: command not found
./cleanLines.txt: line 7: [[Out: command not found
./cleanLines.txt: line 7: [[: command not found
./cleanLines.txt: line 7: [[: command not found


My test.txt file is as follows:

*blank line*(Won't let me edit it like this here)
#Some note
HelloWorld #note
Today is sunny
Cookie Monster

Out of things to say


and cleanLines.txt is as follows:

#!/bin/bash

PATH=${PATH[*]}:.
#filename: clearLines

while read line; do
if [[$line != ""]]; then
.
.
# Doing stuff
.
.
fi
done < test.txt


NOTE: line 7 is:

if [[$line != ""]]; then


What is the problem here? Unless I have to, (since we were strictly told NOT to) I prefer not to post the rest of my code.

Answer

Spaces are important. Replace:

if [[$line != ""]]; then

with:

if [[ $line != "" ]]; then

Examples

Observe that these fail:

$ line=1 ; [[$line != "" ]] && echo yes
bash: [[1: command not found
$ line=1 ; [[ $line != ""]] && echo yes
bash: conditional binary operator expected
bash: syntax error near `yes'

But this version, with the correct spacing, succeeds:

$ line=1 ; [[ $line != "" ]] && echo yes
yes
Comments