1

I wrote a bash-script in CentOs, but now I have an issue with this script in FreeBSD.

So the problem is in difference between "read" function in Linux and "read" function in FreeBSD.


This is a part of my script:

Tmp="an_num.tmp"
Tmpg=$(cat $Tmp)
Tmpi=$(expr $Tmpg + 1)
printf "${WONWARN} Please enter a number ${NORMAL} %s"
read -i "$Tmpi" -e Number; echo
echo "$Number" > "$Tmp"

Here I get a number from an_num.tmp (this file always contains only one number).

Then I Increment this number and put it in Tmpi variable.

After that, I use read function with prefilling (it prefills with Tmpi variable) and user can enter a new value or accept this incremented value.


man read from CentOS:

-i text If readline is being used to read the line text is placed into the editing buffer before editing begins.

But "read" in FreeBSD doesn'have the same -i key.

How can I use prefilling in FreeBSD OS? Thank you.


$ uname -a FreeBSD srv 11.0-RELEASE-p1 FreeBSD 11.0-RELEASE-p1 #0 r306420: Thu Sep 29 01:43:23 UTC 2016 root@releng2.nyi.freebsd.org:/usr/obj/usr/src/sys/GENERIC amd64

  • 2
    This is not a difference between operating systems but between shells. What shell are you using on each of the systems? – Kusalananda Jan 11 '18 at 7:36
  • The read -i feature is bash specific, and only available in bash version 4.0 and above. The Freebsd sh read builtin does not have this feature. – cuonglm Jan 11 '18 at 7:57
  • You are right, It was sh by default, so I changed my default SHELL to bash and succesfully execute it with bash. – rGA145 Jan 11 '18 at 8:33
  • @HelloKatty Just as I told you in your previous question. – arrowd Jan 11 '18 at 8:41
2

If the script is executed by bash on both machines, there will be no issue (at least not if the installed versions of the shell both supports read -i and any other bash-specific feature that the script may use).

Make sure that the script has a proper #!-line pointing to the bash executable on each system.


Notes about the code:

Tmp="an_num.tmp"
Tmpg=$(cat $Tmp)       # may be replaced with Tmpg=$(<"$Tmp")
Tmpi=$(expr $Tmpg + 1) # may be replaced with Tmpi=$(( Tmpg + 1 ))

printf "${WONWARN} Please enter a number ${NORMAL} %s"
# The above lacks a value for the %s format string

read -i "$Tmpi" -e Number; echo
echo "$Number" > "$Tmp"

Alternative implementation (still bash-specific, but works with older versions since it avoids read -i, and it validates that the value read from the user is actually a number/decimal integer):

tmp_fname="an_num.tmp"

read num <"$tmp_fname"
num=$(( num + 1 ))

read -p 'Enter number: '

if [[ -n "$REPLY" ]] && [[ "$REPLY" =~ ^[0-9]*$ ]]; then
    num=$REPLY
fi

echo "$num" >"$tmp_fname"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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