2

I'm creating a tcsh script on the fly (with a static language). I have a <add-command-here> section that contains some command. I want to do:

echo <add-command-here>

In that <add-command-here> I just insert the command. The command should be printed as-is and no evaluated. For example if it contains env $PWD I want it to print $PWD and not the actual path. I thought of wrapping it with single quotes:

echo '<add-command-here>'

But it won't work if the command already have quotes, since here it says:

A single-quote cannot occur within single-quotes.

I also can't use double quotes because it will still evaluate and also it will have the same problem if the command already contains double quotes.

Some tests:

main.py --help
main.py -option1 $PWD
main.py -option1 '$PWD'
'main.py -option1 $PWD'
main.py -option1 "$PWD"
main.py -option1 "PWD 'hi'"
main.py -option1 "PWD \'hi\'"

I want all of them to be printed as-is, meaning if the input is X the output should be X. I'm guessing we need to escape each one of the special char. I will do the implemented by myself (just consider it as a black box - some function that does it). My question only focus on strategy. What is the right way to solve it here?

vesii
  • 203
  • 1
    What are you actually doing with that echo '<add-command-here>' ? Where does that data (the commands to run) come from? – ilkkachu Mar 22 '21 at 22:11
  • 1
    You have tagged your question with the [tag:tcsh] tag. Is tcsh the shell you are working in? – Kusalananda Mar 22 '21 at 22:20
  • Kusalananda, It is tcsh shell. I'll add it to the body of the question itself. ilkkachu, I create this script on the fly (by using Java). This means that I just "print" "echo " + escapeString(cmd) to the script file. And My question tries to figure out what escapeString should do. – vesii Mar 23 '21 at 12:14
  • Shouldn't you be doing this on the Java side? In POSIX-type shells, you just need to quote "$cmd". I haven't used a *csh shell for (sighs) over 20 years. – glenn jackman Mar 23 '21 at 13:40
  • @glennjackman Java creates those scripts that at some point being ran by the users. The question is not about Java because it just creates the scripts and not runs it (or print the command by itself). It just creates the script "on the fly". Wrapping command with quotes have two problems: 1) It will evaluate the cmd (meaning if it has for example $PWD it will print the pwd). 2) What if the cmd already have double quotes? – vesii Mar 23 '21 at 14:02
  • The shell is designed to process (redirections, variable assignments, expansions..) commands before running them. Instead of trying to prevent that processing, strings can be conveniently passed around verbatim as a file and, if you prefer not to use regular files, as a here-document (e.g. cat << "EOT" your_command "EOT"). – fra-san Mar 31 '21 at 10:58

0 Answers0