gpt4 book ai didi

Bash:如何处理所有给定的参数并将它们存储到数组中

转载 作者:行者123 更新时间:2023-11-29 09:32:09 26 4
gpt4 key购买 nike

我是 bash 脚本的初学者,在执行脚本时遇到了问题。

我想处理来自标准输入的所有给定参数。然后我检查这些参数是否是普通文本文件。如果是,我想将它们存储到数组中,稍后我想遍历整个数组。但我收到一个错误:单词 unexpexted在 files+=("$@") 线上我试过这样写 files=("$@")但随后我在该行收到以下错误:“(”意外(期待“fi”)

如果有任何建议,我将不胜感激。提前谢谢你。

for file in "${argv[@]}"; do
if [ -d "$file" ]
then
echo "Error: '"$file"' is directory!" > /dev/stderr
continue
fi


if [[! -f "$file"] || [! -r "$file"]]
then
echo "Error: '"$file"'!" > /dev/stderr
continue
fi

file "$file" | grep text >& /dev/null

if [ ! $status ]
then
files+=("$@")
else
echo "Error: '"$file"' not a text file!" > /dev/stderr
fi
done

for file in "${files[@]}"; do
# .....
done

最佳答案

尝试这样做:

#!/bin/bash

files=( )

for file; do
if ([[ -f "$file && -r "$file" ]] && file "$file" | grep -q -i "text"); then
files+=( "$file" )
fi
done

for f in ${files[@]}; do
# something with "$f"
done

另一个版本,带有错误处理:

#!/bin/bash

files=( )

for file; do
if [[ ! -f "$file ]]; then
echo >&2 "$file is not a regular file"
continue
fi

if [[ ! -r "$file ]]; then
echo >&2 "$file is not readable for $USER"
continue
fi

if ! file "$file" | grep -q -i "text"; then
echo >&2 "$file is not a text file"
continue
fi

files+=( "$file" )
done

for f in ${files[@]}; do
# something with "$f"
done

注意

  • argvbash 中不存在,for file 就足够了
  • 不要使用不存在的变量$status,而是使用预定义的变量$?
  • 无需测试最后状态,您可以做一些更短的操作,例如 grep -q pattern file && do_something
  • echo >&2 表示重定向到STDERR

关于Bash:如何处理所有给定的参数并将它们存储到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13415036/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com