Bash Script to Ash (busybox) - Beginner

Hi All,

I have a script that I wrote on a bash shell, I use it to sort files from a directory into various other directories. I have an variable set, which is an array of strings, I then check each file against the array and if it is in there the script sorts it into the correct folder.

But now I need to move this script to ash, the only part of the script that is giving my bother is the array part, as the other commands are fairly basic commands, if, mv, etc.

I've been searching around but haven't found what I am looking for. Would anyone have any Ideas on how to replace the array in my bash script.

I have an example of what I am doing, obviously in the full script the array is much longer, and there is no point in putting in what I am doing with the files as thats all good.

Essentially, I have the array set, I read the list of files then and using a while loop, I call the sortmove function with then searches the array.

DESTDIR="/destination/"
SORTDIR="/source/"
STRINGS=(
		"string1"
		"string2"
		"string3"
		)



sortmove ()
{
	found=0
	for (( i=0; i<${#STRINGS[@]}; i++ ))
	do
	if [ "${STRINGS[$i]}" == "$3" ];
	then
		do something
	fi
	done
}

ls "${SORTDIR%%/}"/*.mp4 | while read filename
	do
		some processing
		
		sortmove var1 var2 var3
	
	done

Try something like this (not tested):

DESTDIR="/destination/"
SORTDIR="/source/"
STRINGS="string1
string2
string 3"

sortmove ()
{
  found=0
  oldIFS=$IFS
  IFS="
"
  for str in $STRINGS
  do
    if [ "$str" = "$3" ];
    then
      do something
    fi
  done
  IFS=$oldIFS
}

for filename in "${SORTDIR%/}"/*.mp4
do
  some processing

  sortmove var1 var2 var3

done

Since you are not using the array index, I used a simple list of strings with a linefeed as the field separator..

1 Like

Thanks, for the suggestion. I'll give it a shot and will report back on it.

For my enlightenment - you use the linefeed just in case a string should contain a space. If that could be ruled out, a simple space as separator would do as well, wouldn't it?

In that case the regular IFS could be used, i.e. any combination whitespace that consists of spaces, tabs or linefeeds.. So the use of spaces or tabs as field separator would not need to be excluded...

1 Like

So looks like your suggestion was spot on the mark for me. Thanks for that!!