如何在shell脚本中操作数组

vij*_*had 6 linux shell

我希望我的脚本定义一个空数组.如果预定义条件为真,则应添加数组值.为此,我所做的就是

declare -a FILES
file_count=0
if [ "$file_ext" != "$SUPPORTED_FILE_TYPE" ] ; then
        echo "$file_ext is not supported for this task."
else
        $FILES[$file_count] = $filename
        file_count=$file_count+1
fi
Run Code Online (Sandbox Code Playgroud)

执行此脚本时,我收到这样的错误

linux-softwares/launchers/join_files.sh: 51: [0]: not found
Run Code Online (Sandbox Code Playgroud)

Enr*_*sso 3

当数组中的设置数据不能用 $ 调用时:

declare -a FILES
file_count=0
if [ "$file_ext" != "$SUPPORTED_FILE_TYPE" ] ; then
        echo "$file_ext is not supported for this task."
else
        FILES[$file_count]=$filename
        file_count=$file_count+1
fi
Run Code Online (Sandbox Code Playgroud)

不带 $ 的文件。


这对我有用:

#!/bin/bash
declare -a FILES
file_count=0

file_ext='jpg'
SUPPORTED_FILE_TYPE='jpg'
filename='test.jpg'

if [ "$file_ext" != "$SUPPORTED_FILE_TYPE" ] ; then
        echo "$file_ext is not supported for this task."
else
        FILES[$file_count]=$filename
        file_count=$(($file_count+1))
fi
Run Code Online (Sandbox Code Playgroud)

如您所见,对数学运算进行了一些修改 $(( )),但 FILES 分配是相同的......


正如经过大量测试后所指出的,Ubuntu 默认 shell 似乎是 dash,这引发了错误。