As far as I can see, you have no array in your code. The variable msgNumbers
is a string that holds the output of your cut
command.
To iterate over the output of cut
, use
#!/bin/bash mailx -H | grep '^ [UN]' | cut -c 4-5 | while read msg; do print 'msg = %s\s' "$msg" done
This sends the output of cut
into the while
loop immediately following it, through the pipe (|
). The while
loop will iterate with msg
set to each individual line of output from cut
.
The cut
gets its data directly from the grep
command, which removes the need for storing the data in an intermediate file or variable.
I removed the echo $msg|mailx;
command because it did not make much sense to me (the mailx
utility needs an address to send the data to).
The grep
+cut
could also be replaced by a single call to awk
where we let awk
do the work of both tools and output the second whitespace-delimited column when the regular expression matches:
#!/bin/bash mailx -H | awk '/^ [UN]/ { print $2 }' | while read msg; do print 'msg = %s\s' "$msg" done
I'm not commenting further on the use of mailx
as it is a non-standard utility which is implemented slightly differently across Unix systems (my version does not have a -H
option, for example).
The #!
-line looks ok to me, if you want the script to be executed by bash
and if the bash
executable is located at that path (which it commonly is on Linux systems, for example, but check with command -v bash
on your system to be sure). The code I have posted above is compatible with /bin/sh
, so bash
isn't really needed to run it (it would run in any sh
-like shell).
Just make sure that the script is executable and that you run it without specifying an explicit interpreter.