使用find命令在shell中创建数组

时间:2016-01-20 14:16:00

标签: shell

您好我有以下问题:此代码在我的电脑上没有语法错误的shell脚本中运行但在其他服务器上我收到语法错误“(”意外

export data=( $(find "~/" -iname "*.png") )
for i in ${data[@]}
do
    mogrify -crop 1024x794 ${i}
    rm ${i%.png}-1.png
    mv ${i%.png}-0.png ${i}   
done

2 个答案:

答案 0 :(得分:2)

确保使用Bash执行脚本。也许在脚本的第一行添加一个shebang:#! /usr/bin/bash。您也可以在脚本中使用echo $SHELL命令进行检查。 Bash版本也可能不同。在命令行上使用bash --version进行检查。

答案 1 :(得分:1)

接受的答案不符合最佳做法 - 如果文件名名称中包含空格或换行符,则会严重失败。要做到这一点,如果find-print0

#!/bin/bash

data=( )
while IFS= read -r -d '' filename; do
  data+=( "$filename" )
done < <(find ~ -iname '*.png' -print0)

顺便说一句,你根本不需要 需要数组 - 甚至find

#!/bin/sh
# This version DOES NOT need bash

# function to run for all PNGs in a single directory
translate_all() {
  for i in "${1:-$HOME}"/*.png; do
    mogrify -crop 1024x794 "$i"
    rm "${i%.png}-1.png"
    mv "${i%.png}-0.png" "$i"   
  done
}

# function to run for all PNGs in a single directory and children thereof
translate_all_recursive() {
  dir=${1:-$HOME}; dir=${d%/}
  translate_all "$dir"
  for d in "$dir"/*/; do
    translate_all_recursive "$d"
  done
done

# actually invoke the latter
translate_all_recursive

参考文献: