arrays - 如何仅使用 Bash 数组反向打印目录的内容?

标签 arrays linux bash shell reverse

<分区>

目前,我正在做这个家庭作业:

Write a Bash script, reverse.sh, which reverses the contents of a directory passed as a parameter. Assuming /my/dir contains cache cron games lib log run tmp, your program reverse.sh /my/dir will return tmp run log lib games cron cache. Use an array and two functions: main() and reverse(). You will manually manipulate the list as we did today. DO NOT use the built-in command sort -r.

现在,我决定先使用一个函数来获得正确的输出,这不是我的问题。到目前为止,这是我的脚本:

function main(){
    p=$1
    cd $p
    reverse $p
}

function reverse(){
    local p2=$1
    local ARRAY=()
    local count=0
    for entry in $p2*
    do
     ((count++))
     ARRAY+=($entry)
    done
    while [ $count -gt -1 ]; do
     echo ${ARRAY[$count]}
     ((count--))
    done
}
main

但是,无论我在运行脚本时将哪个目录添加为参数,我每次都会得到相同的输出。

最佳答案

p=$1 将不起作用,因为 main 未使用任何参数调用(参数不会自动从命令行传递到函数)。修复是将所有命令行参数传递给函数:

    main $@

关于arrays - 如何仅使用 Bash 数组反向打印目录的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39562787/

相关文章:

bash - 删除所有文件但将所有目录保留在 bash 脚本中?

bash - 一行中 bash 脚本中的文件扩展名列表

javascript - 如何将值从数组放入 Zingchart.js

java - 如果行和列中的所有元素都相同,如何检查二维数组?

linux - 查看 PS 命令的完整输出

linux - 使用Linux原始套接字捕获PTP数据包

python - Linux 上 Python 中的文件和目录

linux - 删除文件中一行的开头

java - 如何将字符串数组转换为字节数组? ( java )

java - 为什么设置变量等于数组索引不能以预期的方式工作?