0

I am getting an error as "getting error as ./array.sh: line 4: syntax error at line 8: `for unmatched " for below code , plz help

#!/bin/ksh
cd /apps/prd/gbl-share/data/transfer/antillia_asset/output
files=(`ls -1t | head -$count`)
echo ${files[@]}

for ((i=0, j=1; i< ${#files[@]}; i++, j++)); do
declare "feed$j"="${files[$i]}"
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
user1763769
  • 103
  • 1
  • 4
  • 11
  • 1
    Don't parse `ls`. If you need to sort by time, there are better ways to do it (and we have other answered questions that go into them). – Charles Duffy Nov 22 '17 at 06:22
  • 2
    ...as for the immediate bug, notice that your `do` doesn't have any `done` following it? – Charles Duffy Nov 22 '17 at 06:22
  • 1
    ...re: sorting by time in a safe and robust manner, this is covered in detail in [BashFAQ #3](http://mywiki.wooledge.org/BashFAQ/003). The example using GNU `find` with `-printf` will work on ksh93 as well. – Charles Duffy Nov 22 '17 at 06:24
  • 2
    (btw, to provide a demonstration that what you're doing right now *isn't* safe and robust, look at what it does when you create a file with `touch $'hello\n*\n * world'`). – Charles Duffy Nov 22 '17 at 06:25
  • 1
    ...related, if not duplicative: [find files in current directory, sort by modified time and store result in an array](https://stackoverflow.com/questions/40982088/find-files-in-current-directory-sorted-by-modified-time-and-store-result-in-an-a). – Charles Duffy Nov 22 '17 at 06:28
  • 1
    @CharlesDuffy That is a cracker for a demo. The op should have a look at [\[ this \]](http://mywiki.wooledge.org/ParsingLs). – sjsam Nov 22 '17 at 06:28

1 Answers1

0

I just replaced the declare with echo and added done at the end of code and it worked .Below is the final code

#!/bin/ksh
cd /apps/prd/gbl-share/data/transfer/antillia_asset/output
files=(`ls -1t | head -6`)
echo ${files[@]}

for ((i=0, j=1; i< ${#files[@]}; i++, j++)); do
 echo  "feed$j"="${files[$i]}"
done
user1763769
  • 103
  • 1
  • 4
  • 11
  • "Worked" only for a very limited value thereof. If you have more interesting filenames (ones with spaces, glob characters, or newlines, to start with), this will fail badly. – Charles Duffy Nov 22 '17 at 13:16
  • ...that said, I'd assumed that the `declare` was doing, well, what you wanted -- assigning a bunch of shell variables, presumably for use by other code below the end of what you posted. If your goal is to *emit code on stdout*, then you want something more like `printf 'feed%q=%q\n' "$j" "${files[$i]}"` to ensure that those files are safe -- you don't want a filename that contains `$(/tmp/some-evil-script)` to be expanded when `eval`ing output. – Charles Duffy Nov 22 '17 at 13:17