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

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

linux-softwares/launchers/join_files.sh: 51: [0]: not found
最佳答案
当数组中的设置数据无法使用$调用时:

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

没有$的文件.

这对我有用:

#!/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

如你所见,对数学运算稍加修改$(()),但FILES分配是相同的……

正如经过大量测试所指出的那样,Ubuntu默认的shell似乎是破折号,这就引发了错误.

相关文章

文章浏览阅读1.8k次,点赞63次,收藏54次。Linux下的目录权限...
文章浏览阅读1.6k次,点赞44次,收藏38次。关于Qt的安装、Wi...
本文介绍了使用shell脚本编写一个 Hello
文章浏览阅读1.5k次,点赞37次,收藏43次。【Linux】初识Lin...
文章浏览阅读3k次,点赞34次,收藏156次。Linux超详细笔记,...
文章浏览阅读6.8k次,点赞109次,收藏114次。【Linux】 Open...