jcast
jcast

Reputation: 1

Unix shell script error in crontab

I'm trying to schedule my shell script but when it triggered to process on a scheduled task, there is this error prompt. but when no files are to be process it just displays the echo command.

here is my code:

if [ "$(ls -A $path)" ]
    then
    for file_name in "$path"/*; do
        filebasename=$(basename "$file_name")


        prefix=${filebasename:0:4};

        if [ "$prefix" == "abcd" ] ; then

            mv  "$file_name" "$out"

        fi                          

    done


    else echo "No files available at $path"
fi

and this is the error:

SH:prefix=${filebasename:0:4}:0403-011 The specified substitution is not valid for this command

Upvotes: 0

Views: 282

Answers (2)

codeforester
codeforester

Reputation: 43109

You can write your code more simply this way:

#!/bin/bash

count=0
if [[ -d "$path" ]]; then
  for file_name in "$path"/abcd*; do
    [[ -f "$file_name" ]] && { ((count++)); mv "$file_name" "$out"; }
  done
fi

if ((count == 0)); then
  echo "No files available at $path"
fi

The advantages:

  • No need to parse the output of ls
  • No need to do basename + substring for each file
  • Skips any directories that have a name starting with abcd

In case you are not interested in knowing whether there were matching files or not, the whole thing can be written in a single line:

find "$path" -name "abcd*" -type f -exec mv "{}" "$out" \;

Upvotes: 1

jcast
jcast

Reputation: 1

i use this code: prefix=$(echo ${filebasename} | cut -c1-4)

instead of prefix=${filebasename:0:4};

now it completely running in my cronjob and no error as said earlier. thanks for the help guys ! :)

Upvotes: 0

Related Questions