2

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

3
  • 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) Commented Jun 6, 2013 at 22:01
  • what happens: A = B : start command A, with arguments "=" and "B" Commented Jun 6, 2013 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 Commented Jun 6, 2013 at 22:03

2 Answers 2

6

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

Comments

1

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"

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.