When you’re writing a DTrace script, often you’d like to pass some parameter in command line. Such an easy task might be really hard unless you read a docs.sun.com section about DTrace scripting, particularly a section about command line parameters macros.
As with sh or bash, you can access command line parameters via $0..$9 macroses. But there’s a catch. Values of these macroses should match a certain definition – a number, an identifier or a string. If there isn’t a match here, you’ll get an error.
Let’s start with a simple script.
#pragma D option quiet BEGIN { #!/usr/sbin/dtrace -s printf("Your parameter: %d\n", $1); }
If you pass a number as a command line parameter, there will be no error, and you’ll get this message:
Your parameter: 123
But if you pass a string instead of number, here’s the error you’ll get:
solaris# ./args.d a1b2c3 dtrace: failed to compile script ./args.d: line 9: failed to resolve a1b2c3: Unknown variable name
This happens because DTrace tries to find an identifier “a1b2c3”. Why does this happen? Because of the way DTrace tries to recognize the type of a command line parameter. The parameter doesn’t look like a number, but to make DTrace accept the value as a string, you have to specify it in quotes. Without them, DTrace accepts we’ve passed an identifier name. And since there isn’t one with such a name, we get an error.
To prove this theory, you simply have to create a variable with the same name in your script:
#!/usr/sbin/dtrace -s #pragma D option quiet BEGIN { a1b2c3=1979; printf("Your parameter: %d\n", $1); }
There you go – it works just like I said:
Your parameter: 1979
And if your parameter is definitely a string, you have to change your script (the line with printf, so that it has %s for a string, and not %d for an integer, otherwise you’ll get another error)…
#!/usr/sbin/dtrace -s #pragma D option quiet BEGIN { a1b2c3=1979; printf("Your parameter: %sn", $1); } ...
and also put your parameter in quotes, like this:
solaris# ./args.d '"a1b2c3"' Your parameter: a1b2c3
As you can see, we’re getting a string we passed, and not the variable with the same name, which was left in the script intentionally to demonstrate it’s not used anymore.
And finally, one more thing. If you want all your command line parameters to be treated as strings by default and even leave the quotes around parameters out, all you have to do is to access the macroses for your parameters with a double $ sign, and then the parameter type definition will be skipped:
#!/usr/sbin/dtrace -s #pragma D option quiet BEGIN { a1b2c3=1979; printf("Your parameter: %s\n", $$1); }
And here’s how you’d access such a script with the same parameter we’ve used before:
solaris# ./args.d a1b2c3 Your parameter: a1b2c3
That’s it for today! Good luck with your DTrace scripts!
geowar says
There isn’t an argc… is there anyway to determine the number of (non-“”) arguments?