zsh-users
 help / color / mirror / code / Atom feed
* cat as a builtin command
@ 2014-08-29  1:40 Izumi Natsuka
  2014-08-29 11:58 ` Roman Neuhauser
                   ` (3 more replies)
  0 siblings, 4 replies; 10+ messages in thread
From: Izumi Natsuka @ 2014-08-29  1:40 UTC (permalink / raw)
  To: zsh-users

Hello, I'm going to write a shell function that provides a basic functionality(print the content of a file or stdin) of cat[0], in order to avoid forking too many process when I call it in a loop[1]. And I have put the following in my zshrc:

cat() {
	if [[ $# -le 1 ]] && [[ ${1:0:1} != '-' || ${1} == '-' ]];then
		local file
		exec {file}<${1:-0}
		read -Erd '' -u ${file}
		exec {file}>&-
	else
		command cat $@
	fi
}

It works perfectly except when I want to cat a binary file:

$ zstat +size archlinux-2012.09.07-dual.iso
411041792
$ cat archlinux-2012.09.07-dual.iso | wc -c
39

Seems that the file was cut by some special raw bytes. As I don't known how to avoid that I tried to use another method(via sysread):

cat() {
	if [[ $# -le 1 ]] && [[ ${1:0:1} != '-' || ${1} == '-' ]];then
		local file REPLY
		exec {file}<${1:-0}
		if [[ -t 1 ]] && [[ $# -eq 0 || ${1} == '-' ]];then
			read -Erd '' -u ${file}
		else
			sysread -i ${file} -o 1 -s $(zstat +size ${1})
		fi
		exec {file}>&-
	else
		command cat $@
	fi
}

It works with raw files. Unfortunately this method doesn't avoid the use of subshell[2], it doesn't fit my need[1] and also doesn't work when you want to cat a fifo.

Is there any way that can perform the basic functionality of cat without calling external command?

Izumi Natsuka

0: https://www.gnu.org/software/coreutils/manual/html_node/cat-invocation.html
1: https://www.ohnekontur.de/2013/02/17/making-cat-a-shell-builtin/
2: http://stackoverflow.com/questions/21976606


^ permalink raw reply	[flat|nested] 10+ messages in thread

end of thread, other threads:[~2014-09-02  1:19 UTC | newest]

Thread overview: 10+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2014-08-29  1:40 cat as a builtin command Izumi Natsuka
2014-08-29 11:58 ` Roman Neuhauser
2014-08-29 12:24 ` Dirk Heinrichs
2014-08-29 13:20   ` Roman Neuhauser
2014-08-29 13:33     ` Dirk Heinrichs
2014-08-29 13:03 ` Peter Stephenson
2014-08-30 10:11   ` Mikael Magnusson
2014-09-01  7:53 ` Han Pingtian
2014-09-01 18:39   ` Bart Schaefer
2014-09-02  1:08     ` Han Pingtian

Code repositories for project(s) associated with this public inbox

	https://git.vuxu.org/mirror/zsh/

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).