Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

bash read Frustration

Status
Not open for further replies.

SamBones

Programmer
Aug 8, 2002
3,186
US
Ok, I'm mostly comfortable with the Korn shell. Since I'm doing some stuff on Linux now I'm trying to use bash a bit more. I'm finding that the '[tt]read[/tt]' command seems broken.

This test script in Korn shell works great...

Code:
#!/bin/ksh

echo $SSH_CONNECTION | read FROM_IP FROM_PORT TO_IP TO_PORT

echo "SSH_CONNECTION = '${SSH_CONNECTION}'"
echo "From = ${FROM_IP}:${FROM_PORT}"
echo "  To = ${TO_IP}:${TO_PORT}"

Code:
[bones@flea ~]$ ./test.ksh
SSH_CONNECTION = '10.8.24.105 58993 10.8.24.54 22'
From = 10.8.24.105:58993
  To = 10.8.24.54:22

Everything working as expected.

Same code in [tt]bash[/tt], not so much...

Code:
#!/bin/bash

echo $SSH_CONNECTION | builtin read FROM_IP FROM_PORT TO_IP TO_PORT

echo "SSH_CONNECTION = '${SSH_CONNECTION}'"
echo "From = ${FROM_IP}:${FROM_PORT}"
echo "  To = ${TO_IP}:${TO_PORT}"

Code:
[bones@flea ~]$ ./test.bash
SSH_CONNECTION = '10.8.24.105 58993 10.8.24.54 22'
From = :
  To = :

I did find online that even though [tt]read[/tt] is a shell builtin command, [tt]bash[/tt] runs it as a subprocess if used in a pipe, thus no variables defined in the parent process. Uh, that effectively breaks it.

I did find that there was a [tt]/usr/bin/read[/tt] that looked like this...

Code:
#!/bin/sh
builtin read "$@"

So I renamed that out of the way, so it's no longer there...

Code:
[bones@flea ~]$ which read
/usr/bin/which: no read in (/usr/lib64/qt-3.3/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/opt/mssql-tools/bin)

The above scripts run exactly the same, [tt]ksh[/tt] as expected, [tt]bash[/tt] broken.

I do have workarounds, but I like this construct. Piping to a [tt]read[/tt] to parse a line is very clean and easy to understand and support. Playing games with [tt]awk[/tt] or [tt]sed[/tt] to parse a line is, well, stupid.

So, all you [tt]bash[/tt] aficionados, am I missing something, or should I stick with the Korn shell?


 
Hi

Use a here-string :
Bash:
[b]builtin read[/b] FROM_IP FROM_PORT TO_IP TO_PORT [teal]<<<[/teal] [i][green]"$SSH_CONNECTION"[/green][/i]
Though did not got why you use the [tt]builtin[/tt] keyword.


Feherke.
feherke.github.io
 
Yeah, with or without "[tt]builtin[/tt]", it still doesn't work as it should. I was just trying that because the [tt]/usr/bin/read[/tt] version had it.

Code:
#!/bin/sh
[b]builtin[/b] read "$@"

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top