简体   繁体   English

Bash shell脚本 - 设置变量时出错

[英]Bash shell scripting - Error setting variables

I'm new at bash scripting. 我是bash脚本的新手。 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. 另外,我正在尝试使用grep从文本文件中提取第二个和第三个单词。 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 任何帮助,将不胜感激

When you assign variables in bash, there should be no spaces on either side of the = sign. 在bash中分配变量时,在=号的两边都不应有空格。

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

For your second problem, use awk not grep . 对于第二个问题,请使用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中的文件的每一行中提取第二和第三项:

< $filename0 awk '{print $2 $3}'

In bash (and other bourne-type shells), you can use a default value if a variable is empty or not set: 在bash(和其他bourne-type shell)中,如果变量为空或未设置,则可以使用默认值:

filename01=${1:-newList01.txt}

I'd recommend spending some time with the bash manual: http://www.gnu.org/software/bash/manual/bashref.html 我建议花一些时间使用bash手册: 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM