Use loop var i within Cut Command

Hi,

In the following bash code rather than cutting at a predefined character I would like to cut at position i (i var from loop).
Is this possible? I have tried eval, but either it's not possible or my syntax is wrong.

thanks

Nick

for i in {1..9}
do
       
        theChar=$(echo "$permissions" | cut -c2)
        checkPermissions $theChar
        charArray=$response
done

This seems to work:

permissions="rwxr-x---"
for i in {1..9}
do
  echo i = $i       
  theChar=$(echo "$permissions" | cut -c$i)
  echo theChar = $theChar
done
$ bash ./arraytest.sh
i = 1
theChar = r
i = 2
theChar = w
i = 3
theChar = x
i = 4
theChar = r
i = 5
theChar = -
i = 6
theChar = x
i = 7
theChar = -
i = 8
theChar = -
i = 9
theChar = -
$

Also I presume that:
charArray
[i]should be
charArray[$i]
?

Not that I have got any of that part of the code working..

http://unstableme.blogspot.com/2008/06/using-array-in-bash-script.html looks helpful on using arrays in shells scripting.

Hi,

Thanks for your prompt reply.
You are right. should be charArray[$i]

cut -c$i seems obvious now. But I couldn't see it for the life of me at the time.

thanks again.

/N

Some more generic solution for this kind of needs. Works every Posix compatible shells (ksh, bash, ...).

# add space after every char (char between space and z)
perm=$( echo "$permissions" | sed "s/[ -z]/& /g"  )
# after that this is easy
i=1
for c in $perm
do
       charArray[$i]=$c
       (( i+=1 ))
done
echo "${#charArray[*]}"
echo "${charArray[*]}"

Or using builtin substr command, not external ex. cut, awk, expr, ...

i=0
len=${#permissions}
while (( i< len ))
do
       charArray[$i]=${permissions:$i:1}
       (( i+=1 ))
done
echo "${#charArray[*]}"
echo "${charArray[*]}"