tags:

views:

35

answers:

2

For some reason this script will work with all of the 'echo's at the end, but without them $wall is an empty string. This seems like really odd behaviour.

#!/bin/zsh

if [ ! -n "$1" ] ; then
    files=(~/pictures/backgrounds/*jpg)
else
    while [ $1 ] ; do
        files+=(`echo $1/*jpg`)
        shift
    done
fi
echo $files
N=${#files}
echo $N
((N=RANDOM%N))
echo $N
wall=${files[$N]}
echo $wall
cp $wall ~/wall.jpg
+3  A: 

This code will sometimes fail because RANDOM%N can result in zero and zsh array indexes start with 1. You should use RANDOM%N+1 instead.

ZyX
That bit was originally in bash. So the echo has nothing to do with it?
Mirai
+1  A: 

You can:

setopt ksharrays

to enable zero-based indexing.

From man zshoptions:

Emulate ksh array handling as closely as possible. If this option is set, array elements are numbered from zero, an array parameter without subscript refers to the first element instead of the whole array, and braces are required to delimit a sub‐ script (${path[2]}' rather than just$path[2]').

Dennis Williamson