How to pass command line arguments with spaces through a variable in bash

前端 未结 2 352
广开言路
广开言路 2021-01-19 10:58

What I\'m trying to achieve is to read command line arguments from a file and invoke a command using them. So essentially I need to pass the arguments through a bash variabl

2条回答
  •  遥遥无期
    2021-01-19 11:24

    If you want to execute your command once for each line found in file.txt, so each line is a separate argument set, you can do this :

    xargs /some/command 

    The xargs utility takes each line it receives on standard input and uses its content as arguments to be provided to the command that is called. If the file contains only one line, it will work and execute the command only once.

    The following solution does the same, but works with functions too:

    while IFS= read -r line
    do
      eval args=\("$line"\)
      command_or_function "${args[@]}"
    done

    Please note that this uses eval, which means that if file.txt contains malicious content, arbitrary code execution could result. You must be 100% certain that the data contained in the file is safe.

    The idea with this technique is that you explode each line into an array (one array element is one argument), and then use an array expansion ("${args[@]}") that expands to a list of all its elements, properly quoted (the quotes around the expansion are important here).

    As an aside, the eval line could be replaced with :

    declare -a args=\($line\)
    

    But $line still gets expanded, so this is no safer than eval.

提交回复
热议问题