Search code examples
sh

creating file with dynamic names in for loop


I'm trying to loop over few linux command and redirect them to a file, I'm having difficulties assigning the file names according to the command names. I'm sure there is a better way to do it but for now this is how I have my script

#!/bin/sh
j=0
fileName=ls
fileName1=date
echo $fileName$j
for item in "ls -l >> /home/Desktop/$fileName$j" "date >>/home/Desktop/$fileName$j";do
        eval $item
        j=$((j+1))
done

The commands works but it does not create the file names as I am expecting to have ls file and date file. considering I have over 20 commands, what is the best way to get the output of those commands in files with name that correlate to their contents.

I have tried to use eval to have dynamic variable names but with no luck.


Solution

  • Never forget eval is only one-character away from evil... (avoid it). POSIX shell, and all typical shells for that matter, allow you to use the set command to set positional parameters as if they had been given on the command line. You can then loop over the positional parameters using a while loop.. You use the shift command to shift the current positional parameter out moving the next parameter down to $1 for execution.

    Using your provided ls and date commands, you could do the following in POSIX shell:

    #!/bin/sh
    
    set "ls" "date"   ## set the positional parameters to desired commands
    
    while [ -n "$1" ]; do   ## while positional parameters remain
      $1                    ## execute the current command (parameter)
      shift                 ## shift next parameter to current position
    done
    

    Example Use/Output

    In a directory with this example file, you wold get:

    $  sh loopcmds.sh
    README                function-multi-array.sh  permute.sh            readver.sh
    arr-fill.sh           hosts                    pinghosts.sh          replace-e-incremental.sh
    createnumbereddir.sh  list-removable.sh        posix-arighmetic.sh   write-heredoc.sh
    createseqdir.sh       loopcmds.sh              postix-arighmetic.sh  zenity-file-select.sh
    dat                   nameref.sh               process-opts.sh
    file.txt              ns_record.sh             readroster.sh
    Sun 11 Dec 2022 11:57:50 PM CST