bashshell脚本-设置变量时出错

bashshell脚本-设置变量时出错,bash,shell,variables,Bash,Shell,Variables,我不熟悉bash脚本。我尝试了以下方法: filename01 = '' if [ $# -eq 0 ] then filename01 = 'newList01.txt' else filename01 = $1 fi 我得到以下错误: ./smallScript02.sh: line 9: filename01: command not found ./smallScript02.sh: li

我不熟悉bash脚本。我尝试了以下方法:

filename01 = ''

if [ $# -eq 0 ]
        then
                filename01 = 'newList01.txt'
        else
                filename01 = $1
fi
我得到以下错误:

./smallScript02.sh: line 9: filename01: command not found
./smallScript02.sh: line 13: filename01: command not found
我想我没有正确处理变量,但我不知道如何处理。此外,我还尝试使用grep从文本文件中提取第二个和第三个单词。该文件看起来像:

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 

当您在bash中分配变量时,
=
符号两边都不应该有空格,任何帮助都将不胜感激

# good
filename0="newList01.txt"
# bad
filename0 = "newlist01.txt"
对于第二个问题,请使用
awk
而不是
grep
。以下内容将从名称存储在
$filename0
中的文件的每一行提取第二项和第三项:

< $filename0 awk '{print $2 $3}'
<$filename0 awk'{print$2$3}'
在bash(和其他bourne类型的shell)中,如果变量为空或未设置,则可以使用默认值:

filename01=${1:-newList01.txt}
我建议您花些时间阅读bash手册:

以下是提取名称的方法:

while read first second third rest; do
    echo $second $third
done < "$filename01"
读取第一个第二个第三个rest时;做
echo$second$third
完成<“$filename01”

我强烈建议您阅读:了解这个陷阱(以及其他许多陷阱!)的解释。(事实上整个网站都有关于bash编程的好信息:参见常见问题解答和指南,也在那里)发生了什么:A=B:start命令A,参数“=”和“B”另一个相关的(和直觉相反):如果[A条件B]:你需要空格,因为“[”实际上是“test”,即一个命令,它接受参数(和选项分析结束“]”作为参数)…也包含在上述链接中