0

I am trying to execute commands from a shell script with arguments from a file. The arguments are being escaped with single quotes and I am not sure how to resolve it.

args.txt

-o foo.o > log

foo.sh

arg=$(cat args.txt)
echo $arg

set -x
./command $arg

output

$ ./foo.sh
-o foo.o > log
+ ./command -o foo.o '>' log

I want to remove the single quotes while executing the command. echo shows no single quotes. I am not able to resolve this so far.

  • `with arguments from a file` and `>` is passed as an argument. Redirection is not an argument. You want to read arguments from the file, or do you want to read arguments and redirections from the file? If the file contained literally for example `-o "abc def" $'\r' "$(echo 123)"` what arguments should such a construct result in? Anyway, you have to _parse_ the content `$arg`, in pseudocode `for i in $arg; do if $i = '>' then next arg is redirection, remove i and next arg from $arg fi; done; if has redirection ./command $arg > $file; else ./command $arg` – KamilCuk Nov 21 '21 at 03:04
  • @KamilCuk I do understand what you are trying to say. The file can contain anything and the argument has to be used safely. However I have been given this project that I wish to automate and I am aware of the files I am using it on. Thanks for the answer I will try it out. – sujayshaunak Nov 21 '21 at 03:20
  • The quotes are just debugging helpers so you can visually distinguish the difference between syntax and data; nothing is actually adding quotes to your command. What's important here is that anything that comes from a variable is _data_, but to be a redirection, `>` has to be _syntax_. – Charles Duffy Nov 21 '21 at 03:22
  • It's possible to transform data into syntax, though doing so creates serious security flaws and is generally a bad idea. If you _did_ want to do so, though, it would look like `eval "./command $arg"` (btw, note the quoting -- it's important; you get subtle bugs without it). – Charles Duffy Nov 21 '21 at 03:23
  • BTW, [BashFAQ #50: I'm trying to put a command in a variable, but the complex cases always fail!](https://mywiki.wooledge.org/BashFAQ/050) is _very_ relevant. So is [BashFAQ #48: Eval command and security issues](https://mywiki.wooledge.org/BashFAQ/048). – Charles Duffy Nov 21 '21 at 03:26

0 Answers0