【问题标题】:Adding files to an array during looping of the directories在目录循环期间将文件添加到数组
【发布时间】:2018-02-02 03:47:22
【问题描述】:

这是我之前关于从循环目录中自动收集所选文件的问题的发展。 这是我的脚本:

   #!/bin/bash
    server=$(pwd)
    results=${server}/results
    output=${server}/simulations

    date=$(date +"%m_%d_%Y")

    for sim in "$output"/* ; do
     if [[ -d $sim ]]; then
      simulation=$(basename "$sim")
      file=( "${sim}"/gromacs* )
      file_name=$(basename "${file}")
      (( ${#file[@]} == 1 )) && [[ -e $file ]] || {
        echo "ERROR: Exactly one file starting with 'gromacs' should exist" >&2
        exit 1
      }
      (cd "${sim}" && exec cp $file "${results}/${simulation}.${date}")
      echo "${file_name} from ${simulation} has been collected!"
     fi
    done

它在循环中创建一个数组并检查目录中的重复文件:

file=( "${sim}"/gromacs* )
          file_name=$(basename "${file}")
          (( ${#file[@]} == 1 )) && [[ -e $file ]] || {
            echo "ERROR: Exactly one file starting with 'gromacs' should exist" >&2
            exit 1
          }

是否可以在循环之外定义这个数组并在每次处理期间将 $file 附加到现有数组中?在脚本结束时,循环完成后,我想打印整个数组 $file 以及已收集的文件列表。

【问题讨论】:

  • 你之前的问题呢?

标签: arrays bash


【解决方案1】:

是的,你可以这样做:

#!/bin/bash
declare -a my_array=()

for sim in $output"/* ; do
    ...
    ... #do some conditions
    my_array+=( "$file" )
done

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    • 2020-10-22
    • 2016-02-12
    • 2019-04-28
    • 2021-03-09
    • 2022-08-09
    • 2019-02-23
    相关资源
    最近更新 更多