Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

I'm new at bash scripting. I tried the following:

filename01 = ''

if [ $# -eq 0 ]
        then
                filename01 = 'newList01.txt'
        else
                filename01 = $1
fi

I get the following error:

./smallScript02.sh: line 9: filename01: command not found
./smallScript02.sh: line 13: filename01: command not found

I imagine that I am not treating the variables correctly, but I don't know how. Also, I am trying to use grep to extract the second and third words from a text file. The file looks like:

1966 Bart Starr QB Green Bay Packers 
1967 Johnny Unitas QB Baltimore Colts 
1968 Earl Morrall QB Baltimore Colts 
1969 Roman Gabriel QB Los Angeles Rams 
1970 John Brodie QB San Francisco 49ers 
1971 Alan Page DT Minnesota Vikings 
1972 Larry Brown RB Washington Redskins 

Any help would be appreciated

share|improve this question
    
I highly recommend you read: mywiki.wooledge.org/BashPitfalls to see this pitfall (and many others!) explained. (actually the whole site is full of good infos on bash programming: see the FAQ and the Guide, as well, there) – Olivier Dulac Jun 6 '13 at 22:01
    
what happens: A = B : start command A, with arguments "=" and "B" – Olivier Dulac Jun 6 '13 at 22:01
    
Another related (and counterintuitive) : if [ a condition b ] : there you NEED the spaces, as "[" is actually "test", ie a command, which takes arguments (and optionnaly a closing "]" as argument) ... also covered in the link(s) above – Olivier Dulac Jun 6 '13 at 22:03

2 Answers 2

In bash (and other bourne-type shells), you can use a default value if a variable is empty or not set:

filename01=${1:-newList01.txt}

I'd recommend spending some time with the bash manual: http://www.gnu.org/software/bash/manual/bashref.html

Here's a way to extract the name:

while read first second third rest; do
    echo $second $third
done < "$filename01"
share|improve this answer

When you assign variables in bash, there should be no spaces on either side of the = sign.

# good
filename0="newList01.txt"
# bad
filename0 = "newlist01.txt"

For your second problem, use awk not grep. The following will extract the second and third items from each line of a file whose name is stored in $filename0:

< $filename0 awk '{print $2 $3}'
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.