stholzm
stholzm

Reputation: 3455

Passing a file as one string argument to a bash function

I have a Bash function that wraps a java command for convenience. The command accepts an argument which is actually JSON and can be somewhat large, so I prefer to store it in a multi-line file.

Here is a simplified example.

The Java program Test just prints out its last command-line argument as-is, with newlines and indentation as in the JSON file. This works:

$ java Test -s test "$(cat test.json)"
{
    "id": 123,
    "name": "Test"
}

Now my Bash function looks like this:

jwt() { java Test $@; }

When I now call the function with the cat "subcommand", the passed argument is broken:

$ jwt -s test "$(cat test.json)"
{
$ jwt -s test "`cat test.json`"
{

The same command lines work in zsh but I'd like to learn how to do this with bash.


Another example - instead of java I'll just use echo.

This works:

$ echo "$(cat test.json)"
{
    "id": 123,
    "name": "Test"
}

Bash function:

e() { echo $@; }

Calling it:

$ e "$(cat test.json)"
{ "id": 123, "name": "Test" }

Surprisingly, the white-space is compressed into single spaces here. Wondering what the difference to Java is.

Upvotes: 1

Views: 283

Answers (1)

Max Fichtelmann
Max Fichtelmann

Reputation: 3504

"$@" is a special case, which correctly preserves arguments as intended.

$ cat Foo.java
public class Foo {
  public static void main(String[] args) {
    for (String arg: args) {
      System.out.println("'"+arg+"'");
    }
  }
}

$ cat foo.sh
#!/bin/sh

foo() {
  java Foo "$@"
}

foo arg1 arg2 "arg 3"

$ sh foo.sh
'arg1'
'arg2'
'arg 3'

Upvotes: 2

Related Questions