Home > Mobile >  How to pass command line arguments to script instead of shell
How to pass command line arguments to script instead of shell

Time:10-02

I have a tcl/tk script that I run through wish. However, I noticed certain command line arguments are passed to wish instead of my script. For example, if I type ./script -h I get the wish help output instead of my scripts help output.

The following code demonstrates this, where puts $arvg should show the command line arguments. If I use arguments that are not used by wish, like "-i", then they are correctly passed to my script and printed out.

#!/usr/bin/env/ wish

puts $argv

How can I ensure the command line arguments get passed to my script instead of the interpreter?

CodePudding user response:

For well-behaved programs, one possible answer would be this:

#!/usr/bin/env -S interpreter --

The interpreter, whatever it is, would treat the -- as the last option argument. Then it would treat the following argument as the script name, and the remaining arguments as arguments to the script.

Alas, wish doesn't obey this convention. While it supports --, that argument means "this is the last argument that wish itself processes; everything else goes to the script". The argument after -- is not treated a script file to read.

The documentation for -- says that the remaining arguments are passed to the script, but I can't see any way of specifying what that script is, if the -- option is used, other than placing it before the --.

Your best bet might be a shell wrapper:

#!/bin/sh
myname=$0
tkscript="${myname%.sh}.tcl"
wish "$tkscript" -- "$@"

The idea is that you have the above script under the name, say, foo.sh. In the same directory as foo.sh, there is a foo.tcl script: the real one.

The idea is that if the above script is invoked as /path/to/foo.sh, it will calculate the adjacent script's name as /path/to/foo.tcl. That is passed as the argument to wish, then the -- option to say "this is the last argument processed by wish" and then the script's own arguments, which are no longer interpreted by wish even if they look like wish options.

You might not want the .sh suffix on it, but just call it by an unsuffixed name like foo, in which case the tkscript assignment simplifies to:

tkscript="${myname}.tcl"
  • Related