How do I pass the contents of a file as a command line parameter

10,766

Solution 1

This can be done using command substitution, like so:

mvn -Dvar_name="$(cat /path/to/file)" # POSIX
mvn -Dvar_name="$(</path/to/file)"    # bash

This has a notable caveat though: all trailing newlines are stripped. If that doesn't matter, though, then that should work.

If you really just want to read one line, you could use read instead, like so:

IFS= read -r line < /path/to/file
mvn -Dvar_name="$line"

Solution 2

For command substitution, you need to use $() or backticks ``.

It is also important that you quote the substitution, or it will expand into multiple arguments if the file contains more than one word. Here are some examples:

mvn -Dvar_name="$(< /path/to/file)" # bash

mvn -Dvar_name="$(cat /path/to/file)" # POSIX
Share:
10,766

Related videos on Youtube

devios1
Author by

devios1

Updated on September 18, 2022

Comments

  • devios1
    devios1 almost 2 years

    I am storing a file path in a file and need to pass the contents of that file as an argument to a shell script, specifically Maven, something like so:

    mvn -Dvar_name=(contents of file)
    

    Would this work:

    mvn -Dvar_name=(cat /path/to/file)
    

    ?