Shell 中字符串变量的赋值注意点

时间:2023-01-21 20:20:02

1. 变量赋值

语法:var="saaaa"

PS: 等号两边不能有空格

2. 脚本示例如下:


#!/bin/sh
# Get bug activity info
# usage get_bug_activity <bug_id_list_file>

if [ $# -lt 2 ]; then
  echo "Usage:";
  echo "$0 <blk_pair_id_list_file> <dir>";
  exit;
fi

if [ ! -d $2 ]; then
    echo "make DIR $2";
    mkdir $2;
fi

echo -e "processing bug list file \033[1;31m$1\033[m";

n=0
m=0
    cat $1 | while read line                                   # read file $1 line by line
    do
        BugID=`echo ${line%%[A-Z]*} | sed  's/[ \t]*$//g'`;  # get Bugid from each line $line, 
                                                                                 # and remove the space of the string tail
                                                                                 # PS: BugID="***" right; BugID = "***" wrong
                                                                                 # There should no space between "=
        let n=n+1;
        echo -e "\033[1;35m$n\033[m $BugID";
        rfile="$2/a$BugID.htm";
        if [ ! -f "$rfile" ]; then
                curl "https://bugs.eclipse.org/bugs/show_activity.cgi?id=$BugID" -o "$rfile";
        else
                let m=m+1;
                echo -e "\033[1;31mfile existed...\033[m $m duplicated";
        fi
    done

echo "finished";

3. 示例讲解

  1. echo -e "processing bug list file \033[1;31m$1\033[m"; : 用来设置变量$1 的颜色。 \033[1;31m 红色文字 \033[m .
  2. 逐行读取文件内容到 $line

    cat $1 | while read line                                   # read file $1 line by line
    do
            ## do something
    done
  3. 将读到的内容只截取第一个字段 (后面可能会有一些空格): echo ${line%%[A-Z]*}.
  4. 用sed 删除字符串最后的空格 :echo ${line%%[A-Z]*} | sed 's/[ \t]*$//g
  5. 访问网址,并输出到文件 $rfile
    curl "https://bugs.eclipse.org/bugs/show_activity.cgi?id=$BugID" -o "$rfile"