Geo
Geo

Reputation: 96947

How can I pass each filename to my function?

I'm trying to write a simple function that will allow me to interactively unstage files from Git. Here's what I have so far:

reset_or_keep () {
  echo "Received $1"
}

interactive_reset () {
  local mods=
  mods=`git status --porcelain | sed -e "s/^[A-Z][ \t]*//g" | xargs reset_or_keep`
}

However, I receive this error:

xargs: reset_or_keep: No such file or directory

I would like that reset_or_keep is called once for every entry in git status --porcelain

Upvotes: 1

Views: 103

Answers (1)

rra
rra

Reputation: 3887

The easiest way is to effectively reimplement xargs directly in bash using read:

#!/bin/sh

reset_or_keep () {
    echo "Received $1"
}

handle_files() {
    while read filename ; do
        reset_or_keep "$filename"
    done
}

git status --porcelain | sed -e "s/^[ \t]*[A-Z][ \t]*//g" | handle_files

(Note that I had to make a small change to your sed expression to handle the output format from my git status.)

Be aware that, as with xargs without the -0 flag, this program will not work correctly with file names containing whitespace.

Upvotes: 3

Related Questions