我的脚本正在从 grep 结果设置数组,这样空的 grep 结果也存储在数组中。
例如。
set -x
echo "${Arr[@]}"
+ echo '' 'word' '' 'word2'
Run Code Online (Sandbox Code Playgroud)
有人可以帮助取消设置这些空值,以便 echo "${#Arr[@]}" 给出 2 而不是 4
尝试过
var=-1 && for i in "${Input_Arr[@]}"; do var=$((var+1)); if [ -z "$i" ]; then unset "${Input_Arr[$var]}"; fi; done
Run Code Online (Sandbox Code Playgroud)
但它不起作用
我的脚本的工作原理如下:
./script file1 file2 file3 ... -x -st -i
Run Code Online (Sandbox Code Playgroud)
或者
cat filelist.txt | ./script -x -st -i
Run Code Online (Sandbox Code Playgroud)
或者
./script <<< "$(cat filelist) -x -st -i
Run Code Online (Sandbox Code Playgroud)
有人可以帮助使用从文件名设置数组的常用函数,以防文件由位置参数或管道或重定向给出
如何在单个 shell 脚本中涵盖上述所有情况?
尝试过:
input="$(</dev/stdin)"
Arr_tmp+=("$@")
if ! echo "${Arr_tmp[@]}" | grep 'file_regex'; then Array+=( $(echo "$input") ); else Array+=("$(echo "$@" | grep 'file_regex')"); fi
Run Code Online (Sandbox Code Playgroud)
或者
input="$(</dev/stdin)"
IFS=$'\n' read -ra Array -d '' <<< "$(echo $input)"
if [[ "${#Array[@]}" == 0 ]]; then
Arr_tmp+=("$@")
fi
Run Code Online (Sandbox Code Playgroud)
但没有任何作用
上述问题是当没有标准输入通过管道传输时,脚本在读取时被击中。如果没有通过管道传输标准输入,是否有办法防止脚本读取并回退到参数?