2

code

s='id;some text here with possible ; inside'
IFS=';' read -r id string <<< "$s"
echo "$id"

error

restore.sh: 2: restore.sh: Syntax error: redirection unexpected

bash version GNU bash, version 4.2.37(1)-release (x86_64-pc-linux-gnu)

Community
  • 1
  • 1
clarkk
  • 27,151
  • 72
  • 200
  • 340

5 Answers5

11

A here string is just a shortcut for a small here document. This should work in any POSIX shell:

s='id;some text here with possible ; inside'
IFS=';' read -r id string <<EOF
$s
EOF
echo "$id"
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Am new to shell but from Java background. Can you explain your code ? – Jess Mar 25 '19 at 21:37
  • @Jess: very late comment but anyway, my two cents: POSIX `read` expects a line on standard input, reads that and splits it using $IFS contents as a separator, then assigns each chunk to variables given as arguments to `read` (`id` and `string`; `id` getting the first chunk and `string` getting all the remaining chunks). The trick with the two EOFs is called a "heredoc" and AFAIK is the only way to send that string to `read`'s standard input. See also https://pubs.opengroup.org/onlinepubs/9699919799/utilities/read.html. – yassen Oct 12 '21 at 06:56
6

You seem to be using sh to execute the script. Herestrings aren't supported in sh; hence the error.

Ensure that you're using bash to execute the script.

devnull
  • 118,548
  • 33
  • 236
  • 227
1

save it in file split

#!/bin/sh

string=$1
c=0

while [ $c -le $3 ] 
do

val1=`echo "$string" |sed 's/\(^[^'$2']*\)\('$2'\+\)\(.*$\)/\1/'`
string=`echo "$string" |sed 's/\(^[^'$2']*\)\('$2'\+\)\(.*$\)/\3/'`

if [ "$val1" == "$string" ]
then
string=''
fi

if [ "$val1" == "" ]
then
let c=$3
fi

let c=c+1

done

echo $val1 

and it work:

root@IPHONE:~# ./split 'a;b;c' ';' 0
a
root@IPHONE:~# ./split 'a/b/c' '\/' 0
a
root@IPHONE:~# ./split 'a/b/c' '\/' 2
c
root@IPHONE:~# ./split 'a/b/c' '\/' 1
b
0

My result:

[root@localhost ~]# bash --version
GNU bash, version 3.2.25(1)-release (i686-redhat-linux-gnu)
Copyright (C) 2005 Free Software Foundation, Inc.
[root@localhost ~]# ./bash
id
[root@localhost ~]# cat bash
s='id;some text here with possible ; inside'
IFS=';' read -r id string <<< "$s"
echo "$id"

Worked here.

alacerda
  • 155
  • 1
  • 8
-1

I have used python2.7 below:

#!/bin/sh

s='id;some text here with possible ; inside'
python -c "ifc, s =';', '$s';print s.split(';')[0] if ifc in s else ''"

Result:

 $ ./test.sh
id
Michael Kazarian
  • 4,376
  • 1
  • 21
  • 25