0

Is there a way to build a varible like this:

var="-i \"/path to/file 1.mp4\" -i \"/path to/file 2.mp4\""

And then use this later in a program:

ffmpeg $var

I know \" doesn't work, and eval works in a way, but eval can be ugly.

Is there a solution without eval?

3
  • Does the way you've built the variable in your question not work? It looks fine to me. Also, what shell? POSIX? bash? If you're using a more advanced shell like bash/zsh/ksh/fish, you might get useful results by reading the documentation about Arrays. Commented Jun 8, 2016 at 20:09
  • @ghoti This is attempt is not fine. The intention is for $var to expand to 4 arguments, but in this example it expands to 8 in a POSIX-compliant shell: -i, "/path, to/file, 1.mp4", -i, "/path, to/file, and 2.mp4". The embedded quotes are literal characters that do not protect the surrounded whitespace from word-splitting. Commented Jun 9, 2016 at 4:18
  • @chepner Right, of course, I should have been more explicit. The expansion works with word splitting as expected using eval; my test was to do the assignment as shown, then eval set -i $var, then inspect $1, $2, etc. If you can trust your input not to break things, there's little harm in using eval. If the OP's shell supports it, I still think a simple array might be the way to go. Commented Jun 9, 2016 at 17:28

1 Answer 1

1

The next best thing to do is to build an array. When you put ${var[@]} somewhere, it will replace it with the complete array contents. If you put "${var[@]}" somewhere (with quotes), the elements of the array will be quoted, so elements with spaces will not be split at the whitespace into multiple elements:

#!/bin/bash

function test() {
    for ((i=0; i<$#; i++)) {
        echo "Param $i: ${!i}"
    }
}

var[0]="-i"
var[1]="/a/path"
var[2]="-i"
var[3]="/second/path with space/"

test "${var[@]}"

Will output:

Param 0: test.sh
Param 1: -i
Param 2: /a/path
Param 3: -i

and that is exactly what you require. I only tried this in bash, other shells may behave differently.

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

2 Comments

Thank you Dennis! This is exactly what I need! And the array fits also perfect in my script.
Nice to see I could help!

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.