在 for 循环中将文本文件中的行传递到脚本中

在 for 循环中将文本文件中的行传递到脚本中

下面我有一个正在运行的脚本,用于查找在 Ubuntu 上运行的对象存储架构中的文件大小。我遇到的问题是脚本是为一次检查一个帐户而编写的,效果很好,但如果我想修改它以依次解析多个帐户,这怎么可能。有没有办法从另一个文本文件传递参数列表来替换脚本顶部的变量?

例如,如果另一个文本文件 test.txt 包含以下行:

auto02 FfiBftkjgS8hnQn79Arj7PiHfvtsgn
qa04 s67aeYD6521pPgt7TknvGxKvF9WxNF

是否可以从上面的文件中获取用户和密钥,并以某种循环方式将其替换为该脚本顶部的变量以遍历所有帐户?

#!/bin/bash

# Variables to be set
auth=http://sslabapi/auth/v1.0 # Auth URL
user=qa04 # Username
key=s67aeYD6521pPgt7TknvGxKvF9WxNF # Password
size=500000 # Minimum file size in bytes

# Env variables set
ST_AUTH="$auth"
ST_USER="$user"
ST_KEY="$key"

# Env variables exported
export ST_AUTH
export ST_KEY
export ST_USER

# Timestamp function
timestamp() {
    date +"%Y-%m-%d %T"
}

# Main Loop
containerList="$(swift list)"
echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" >> bigFiles.txt
echo "$(timestamp): Account for $user" >> bigFiles.txt
echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" >> bigFiles.txt
echo "Starting check for files > $size bytes in the $user user account..."
for i in $containerList; do
    echo "*************************" >> bigFiles.txt
    echo "Container $i" >> bigFiles.txt
    echo "*************************" >> bigFiles.txt
    echo "Container $i"
    IFS=$'\n'
    olist=($(swift list -l $i))
    for a in ${olist[@]}; do
        osize=`echo "$a" | awk '{print $1}'`
        if [ $osize -gt "$size" ]; then
            echo "Found one: $a"
            echo "$a" >> bigFiles.txt
        fi
    done
done

以下是我的脚本的编辑版本,其中提供了添加内容:

#!/bin/bash

while read -r user key
do
# Variables to be set
auth=http://sslabapi/auth/v1.0 # Auth URL
#user=$user # Username
#key=$key # Password
size=500000 # Minimum file size in bytes

# Env variables set
ST_AUTH="$auth"
ST_USER="$user"
ST_KEY="$key"

# Env variables exported
export ST_AUTH
export ST_KEY
export ST_USER

# Timestamp function
timestamp() {
    date +"%Y-%m-%d %T"
}

# Main Loop
containerList="$(swift list)"
echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" >> bigFiles.txt
echo "$(timestamp): Account for $user" >> bigFiles.txt
echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" >> bigFiles.txt
echo "Starting check for files > $size bytes in the $user user account..."
for i in $containerList; do
    echo "*************************" >> bigFiles.txt
    echo "Container $i" >> bigFiles.txt
    echo "*************************" >> bigFiles.txt
    echo "Container $i"
    IFS=$'\n'
    olist=($(swift list -l $i))
    for a in ${olist[@]}; do
        osize=`echo "$a" | awk '{print $1}'`
        if [ $osize -gt "$size" ]; then
            echo "Found one: $a"
            echo "$a" >> bigFiles.txt
        fi
    done
done
echo "...finished check!"
done < test.txt

答案1

您只需while在起始即添加一个简单的循环即可

while IFS=' ' read -r user key
 do
  Your whole script
 done < test.txt

相关内容