Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Am trying to get a substring from a string but am getting the error: ${curr_rec:3:4}: bad substitution

#!/bin/ksh

get_file_totals()
{

    if [ -e "$file_name" ]
    then
        IFS=''
        while read line
        do
        curr_rec=$line
        echo ${curr_rec:3:4}
        done < "$file_name"
    else

        echo "error"
    fi
}

file_name="$1"
get_file_totals
share|improve this question
    
It's working for me. How do you call the script? –  chaos May 27 at 9:36
    
FWIW I get this error if I (wrongly) call the script like sh myscript. I can't reproduce it otherwise. –  roaima May 27 at 10:06
1  
You may want to read Why is using a shell loop to process text considered bad practice?. You've fallen in almost every trap there. –  Stéphane Chazelas May 27 at 10:54

2 Answers 2

up vote 1 down vote accepted

It would be more efficient to rewrite this, thereby avoiding the issue in the first place:

#!/bin/ksh

get_file_totals()
{

    if [ -e "$file_name" ]
    then
        cut -c4-7 "$file_name"
    else
        echo "error"    # consider stderr by appending >&2
    fi
}

file_name="$1"
get_file_totals
share|improve this answer

You're invoking ksh. The kind of substitution you are wanting to do works only since ksh '93. Is there a chance you are using an older version? Run ksh and check for the existence of KSH_VERSION. If it doesn't exist or is before '93, it's too old.

share|improve this answer
    
That syntax is also available in zsh's ksh and mksh since version 30.1 (2007). –  Stéphane Chazelas May 27 at 10:58
    
(with mksh, you need the -U option for ${var:offset:length} to work with characters as opposed to bytes in UTF-8 locales). –  Stéphane Chazelas May 27 at 11:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.