sh - 通过分隔符拆分字符串

cla*_*rkk 2 linux bash sh herestring

s='id;some text here with possible ; inside'
IFS=';' read -r id string <<< "$s"
echo "$id"
Run Code Online (Sandbox Code Playgroud)

错误

restore.sh: 2: restore.sh: Syntax error: redirection unexpected
Run Code Online (Sandbox Code Playgroud)

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

che*_*ner 9

这里的字符串只是一个小文档的快捷方式.这适用于任何POSIX shell:

s='id;some text here with possible ; inside'
IFS=';' read -r id string <<EOF
$s
EOF
echo "$id"
Run Code Online (Sandbox Code Playgroud)


dev*_*ull 6

您好像用来sh执行脚本.不支持Herestrings sh; 因此错误.

确保您bash用于执行脚本.

  • 这适用于`echo"$ s"| cut -d";" -f1`但是如何将其分配给变量? (2认同)