Help us understand the problem. What is going on with this article?

Windowsではxargsではなくwhileを使う

More than 1 year has passed since last update.

Summary

windowsでのxargsは引数に関数をもってこれない(正確にいうと export -f ができない)ので while をつかう

environment

windowsでbashを使うためにbusybox.exeを同一フォルダに入れておく

$ ver
ver

Microsoft Windows [Version 10.0.18362.239]

$ tree
Active code page: 437
Folder PATH listing
Volume serial number is 80A0-D9ED
C:\USERS\MOCHI\SAMPLE_XARGES
    bar.cmd
    busybox.exe
    foo.bash
    foo.cmd

No subfolders exist 

bashでのコード

foo.bash
#! /usr/bin/env bash

function foo () {

  echo "Hello "$1

}

function main () {

  local x="nor135 ytez callmekohei"

  export -f foo

  echo $x | tr ' ' '\n' \
    | xargs -I{} bash -c 'foo {}'

}

main

結果

Hello nor135
Hello ytez
Hello callmekohei

windowsでのコード(xargs)

foo.cmd
: <<EOF_BAT
@echo off
"%~dp0busybox.exe" bash "%~f0" %*
exit /b %ERRORLEVEL%
EOF_BAT

#! /usr/bin/env bash

function foo () {

  echo "Hello "$1

}

function main () {

  local x="nor135 ytez callmekohei"

  export -f foo

  echo $x | tr ' ' '\n' \
    | xargs -I{} bash -c 'foo {}'

}

main

結果

C:/Users/mochi/sample_xarges/foo.cmd: export
: line 19: illegal option -f

windowsでのコード(while)

bar.cmd
: <<EOF_BAT
@echo off
"%~dp0busybox.exe" bash "%~f0" %*
exit /b %ERRORLEVEL%
EOF_BAT


#! /usr/bin/env bash

function foo () {
  echo "Hello "$1
}

function main () {

  local x='nor135 ytez callmekohei'

  echo  "$x" | tr ' ' '\n' \
    | while read -r twitterID
      do
        foo $twitterID
      done

}

main

結果

Hello nor135
Hello ytez
Hello callmekohei

現場からは以上です

callmekohei
コーヒー飲みながらぼんやりとF#書くのが好きです。
fukuokaex
エンジニア/企業向けにElixirプロダクト開発・SI案件開発を支援する福岡のコミュニティ
https://fukuokaex.fun/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away