0

When you define a bash function you can call bash commands with command command.

function ls() {
  clear
  command ls "$@"
}

How would you pipe commands in bash function?

e.g.

function ls() {
  clear
  command ls "$@" | head
}

EDIT: The output would be OK, but there is --color=auto. Look here

11
  • What are you trying to achieve here? Commented Nov 15, 2011 at 13:45
  • ls function will be clear; ls | head , but I want function, not alias Commented Nov 15, 2011 at 13:47
  • Are you trying to override the builtin ls? Commented Nov 15, 2011 at 13:50
  • What's the problem with your function? Works for me. Commented Nov 15, 2011 at 14:07
  • 1
    I would just name the alias another way. What if a script depended on how ls works? Commented Nov 15, 2011 at 14:20

2 Answers 2

3

Try this in your ~/.bashrc

function ls() { clear ; builtin ls "$@" | head ; }

It's similar to the function you have already but with the inclusion of builtin, it guarantees not to get stuck in a loop calling itself. Hope this works!

EDIT: It should be noted that any colour information produced by ls with the --color=auto option won't be carried through the pipe to head.

Sign up to request clarification or add additional context in comments.

Comments

1

You can pipe the colour information generated by the ls command to head if you run ls in a so-called pseudo terminal (so that ls thinks it is writing its output to a terminal, and not a pipe). This can be achieved by using the script command.

ls() {
   type -P command 1>/dev/null || 
        { echo 'No "command" executable found!'; return 1; }
   clear
   script -q /dev/null command ls -G "$@" | tr -d '\r' | head
 }


 cat /usr/bin/command   # on Mac OS X 10.6.8
 #!/bin/sh
 # $FreeBSD: src/usr.bin/alias/generic.sh,v 1.2 2005/10/24 22:32:19 cperciva Exp $
 # This file is in the public domain.
 builtin `echo ${0##*/} | tr \[:upper:] \[:lower:]` ${1+"$@"}

For more information see: ls command operating differently depending on recipient

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.