Program name: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎{{header|Wren}}: Minor tidy)
(26 intermediate revisions by 19 users not shown)
Line 7: Line 7:


Examples from [https://github.com/mcandre/scriptname GitHub].
Examples from [https://github.com/mcandre/scriptname GitHub].

=={{header|11l}}==
<syntaxhighlight lang="11l">:start:
print(‘Program: ’:argv[0])</syntaxhighlight>
=={{header|68000 Assembly}}==
{{works with|NEOGEO}}
The name of the game is stored on the cartridge at memory address $000200. It is exactly 16 characters and is padded with spaces (ASCII 32). Since there is no null terminator after this string, use its size to terminate a printing loop.

<syntaxhighlight lang="68000devpac">LEA $000200,A3
JSR PrintString ;(my print routine is 255-terminated and there just so happens to be an FF after the name of the game.)</syntaxhighlight>

;Output
[[https://ibb.co/4jNm7TW Ninja Adventure]]


=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
Line 14: Line 27:
Without built-in CRT, <code>argc</code> and <code>argv</code> are stored in the stack. The format looks like:
Without built-in CRT, <code>argc</code> and <code>argv</code> are stored in the stack. The format looks like:


<lang>sp+0 = argc
<syntaxhighlight lang="text">sp+0 = argc
sp+8 = argv[0]
sp+8 = argv[0]
sp+16 = argv[1] ...</lang>
sp+16 = argv[1] ...</syntaxhighlight>


Each item of <code>argv</code> is a pointer to a null-terminated 8-bit string.
Each item of <code>argv</code> is a pointer to a null-terminated 8-bit string.


<lang ARM_Assembly>.equ STDOUT, 1
<syntaxhighlight lang="arm_assembly">.equ STDOUT, 1
.equ SVC_WRITE, 64
.equ SVC_WRITE, 64
.equ SVC_EXIT, 93
.equ SVC_EXIT, 93
Line 63: Line 76:
_exit:
_exit:
mov x8, #SVC_EXIT
mov x8, #SVC_EXIT
svc #0</lang>
svc #0</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
Being a compiled language, Ada has difficulties accessing source code filenames. But it is easy to access the executable's filename, using the function Command_Name defined in Ada.Command_Line:
Being a compiled language, Ada has difficulties accessing source code filenames. But it is easy to access the executable's filename, using the function Command_Name defined in Ada.Command_Line:
<lang Ada>with Ada.Command_Line, Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Command_Line, Ada.Text_IO;


procedure Command_Name is
procedure Command_Name is
begin
begin
Ada.Text_IO.Put_Line(Ada.Command_Line.Command_Name);
Ada.Text_IO.Put_Line(Ada.Command_Line.Command_Name);
end Command_Name;</lang>
end Command_Name;</syntaxhighlight>


=={{header|Aime}}==
=={{header|Aime}}==
The program command line arguments are accessible via the argc()/argv() functions. The program name is the first in the list of arguments.
The program command line arguments are accessible via the argc()/argv() functions. The program name is the first in the list of arguments.
<lang aime>o_text(argv(0));
<syntaxhighlight lang="aime">o_text(argv(0));
o_byte('\n');</lang>
o_byte('\n');</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang>
<syntaxhighlight lang="text">
BEGIN
BEGIN
print ((program idf, newline))
print ((program idf, newline))
END
END
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
$ a68g Program_name.a68
$ a68g Program_name.a68
Program_name.a68
Program_name.a68
$
</pre>

=={{header|Amazing Hopper}}==
El primer parámetro en Hopper y sus sabores, siempre será el nombre del programa.
<syntaxhighlight lang="amazing hopper">
#include <hbasic.h>
Begin
GetParam(name File)
Print("My Program name: ", name File,Newl)
End
</syntaxhighlight>
{{out}}
<pre>
$ hopper myname.bas
My Program name: myname.bas
$
$
</pre>
</pre>


=={{header|Applesoft BASIC}}==
=={{header|Applesoft BASIC}}==
<syntaxhighlight lang="applesoftbasic">
<lang ApplesoftBASIC>
10 GOSUB 40"GET PROGRAM NAME
10 GOSUB 40"GET PROGRAM NAME
20 PRINT N$
20 PRINT N$
Line 155: Line 184:
670 N$ = "
670 N$ = "
680 RETURN
680 RETURN
</syntaxhighlight>
</lang>


=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>


/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
Line 215: Line 244:
bx lr /* retour procedure */
bx lr /* retour procedure */
</syntaxhighlight>
</lang>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">
<lang AutoHotkey>
MsgBox, % A_ScriptName
MsgBox, % A_ScriptName
</syntaxhighlight>
</lang>


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: TAWK -f PROGRAM_NAME.AWK
# syntax: TAWK -f PROGRAM_NAME.AWK
#
#
Line 242: Line 271:
exit(0)
exit(0)
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 261: Line 290:


Unlike most MS BASICs, [[FreeBASIC]] provides a parsed version of <code>[http://www.freebasic.net/wiki/wikka.php?wakka=KeyPgCommand COMMAND$]</code> (called as <code>COMMAND$(n)</code>). <code>COMMAND$(0)</code> is the program's name:
Unlike most MS BASICs, [[FreeBASIC]] provides a parsed version of <code>[http://www.freebasic.net/wiki/wikka.php?wakka=KeyPgCommand COMMAND$]</code> (called as <code>COMMAND$(n)</code>). <code>COMMAND$(0)</code> is the program's name:
<lang qbasic>appname = COMMAND$(0)</lang>
<syntaxhighlight lang="qbasic">appname = COMMAND$(0)</syntaxhighlight>


Additionally, FreeBASIC also provides an analog of [[#C|C's]] <code>argc/argv[]</code>, called <code>[http://www.freebasic.net/wiki/wikka.php?wakka=KeyPgDdfbargc __FB_ARGC__]</code> and <code>[http://www.freebasic.net/wiki/wikka.php?wakka=KeyPgDdfbargv __FB_ARGV__]</code>. __FB_ARGV__ can be used to get the program's name like this:
Additionally, FreeBASIC also provides an analog of [[#C|C's]] <code>argc/argv[]</code>, called <code>[http://www.freebasic.net/wiki/wikka.php?wakka=KeyPgDdfbargc __FB_ARGC__]</code> and <code>[http://www.freebasic.net/wiki/wikka.php?wakka=KeyPgDdfbargv __FB_ARGV__]</code>. __FB_ARGV__ can be used to get the program's name like this:
<lang qbasic>appname = *__FB_ARGV__(0)</lang>
<syntaxhighlight lang="qbasic">appname = *__FB_ARGV__(0)</syntaxhighlight>


See also: [[#PowerBASIC|PowerBASIC]], [[#PureBasic|PureBasic]], [[#Visual Basic|Visual Basic]].
See also: [[#PowerBASIC|PowerBASIC]], [[#PureBasic|PureBasic]], [[#Visual Basic|Visual Basic]].
Line 270: Line 299:
==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> SYS "GetCommandLine" TO cl%
<syntaxhighlight lang="bbcbasic"> SYS "GetCommandLine" TO cl%
PRINT $$cl%</lang>
PRINT $$cl%</syntaxhighlight>


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 PROGRAM "Name1.bas"(A,B,C,S$)
<syntaxhighlight lang="is-basic">100 PROGRAM "Name1.bas"(A,B,C,S$)
110 CHAIN "Name2.BAS"(A,B,C,S$)
110 CHAIN "Name2.BAS"(A,B,C,S$)


Line 282: Line 311:


edit 0
edit 0
start(1,2,3,"Hello")</lang>
start(1,2,3,"Hello")</syntaxhighlight>

==={{header|BaCon}}===
To get the name with which the program was invoked:
<syntaxhighlight lang="bacon">PRINT TOKEN$(ARGUMENT$, 1)</syntaxhighlight>
To get the full path:
<syntaxhighlight lang="bacon">PRINT ME$</syntaxhighlight>
==={{header|uBasic/4tH}}===
'''CMD(1)''' returns a string with the filename - '''SHOW()''' prints this string.
<syntaxhighlight lang="text">Print Show(Cmd(1))</syntaxhighlight>

=={{header|Blue}}==

Linux/x86-64. Will print the name of the executable from "argv[0]" as provided.

<syntaxhighlight lang="blue">global _start

: syscall ( num:eax -- result:eax ) syscall ;

: exit ( status:edi -- noret ) 60 syscall ;
: bye ( -- noret ) 0 exit ;

: write ( buf:esi len:edx fd:edi -- ) 1 syscall drop ;

1 const stdout

: print ( buf len -- ) stdout write ;

: newline ( -- ) s" \n" print ;
: println ( buf len -- ) print newline ;

: find0 ( start:rsi -- end:rsi ) lodsb 0 cmp latest xne ;
: cstrlen ( str:rdi -- len:rsi ) dup find0 swap sub dec ;
: cstr>str ( cstr:rdx -- str:rsi len:rdx ) dup cstrlen xchg ;

: print-arg ( arg -- ) cstr>str println ;

: arg0 ( rsp -- rsp ) 8 add @ ; inline

: _start ( rsp -- noret ) arg0 print-arg bye ;</syntaxhighlight>

=={{header|BQN}}==
<syntaxhighlight lang="bqn">•name</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
Line 289: Line 360:
* <code>argv[0]</code> might be the name of an executable in the PATH, or it might be an absolute or relative path to the executable. At least with [[Unix]], the parent process can set <code>argv[0]</code> to any string, so <code>argv[0]</code> might not be the real name. It is best to pretend that <code>argv[0]</code> has the correct value, but mind that <code>argv[0]</code> might not be an actual file.
* <code>argv[0]</code> might be the name of an executable in the PATH, or it might be an absolute or relative path to the executable. At least with [[Unix]], the parent process can set <code>argv[0]</code> to any string, so <code>argv[0]</code> might not be the real name. It is best to pretend that <code>argv[0]</code> has the correct value, but mind that <code>argv[0]</code> might not be an actual file.


<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>


int main(int argc, char **argv) {
int main(int argc, char **argv) {
Line 295: Line 366:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


To get the source information about some part of code, use compiler defined macros. Most compilers support them or some variation of.
To get the source information about some part of code, use compiler defined macros. Most compilers support them or some variation of.
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
int main()
int main()
Line 305: Line 376:
__FILE__, __FUNCTION__, __LINE__);
__FILE__, __FUNCTION__, __LINE__);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=== BSD ===
=== BSD ===
Line 318: Line 389:
{{works with|OpenBSD|5.0}} '''To compile myname.c:''' <code>make myname LDLIBS=-lkvm</code>
{{works with|OpenBSD|5.0}} '''To compile myname.c:''' <code>make myname LDLIBS=-lkvm</code>


<lang c>/* myname.c */
<syntaxhighlight lang="c">/* myname.c */


#include <sys/param.h>
#include <sys/param.h>
Line 354: Line 425:
kvm_close(kd);
kvm_close(kd);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


The program can have three different names!
The program can have three different names!
Line 367: Line 438:


{{libheader|Win32}}
{{libheader|Win32}}
<lang c>#include <windows.h>
<syntaxhighlight lang="c">#include <windows.h>
#include <stdlib.h>
#include <stdlib.h>
#include <wchar.h>
#include <wchar.h>
Line 423: Line 494:
free(path);
free(path);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


<pre>Path to executable: C:\Users\kernigh\Documents\field\scratch.exe</pre>
<pre>Path to executable: C:\Users\kernigh\Documents\field\scratch.exe</pre>
Line 429: Line 500:
=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
This effectively outputs the executable name, file path, and any arguments for the current program.
This effectively outputs the executable name, file path, and any arguments for the current program.
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
namespace ProgramName
namespace ProgramName
{
{
Line 439: Line 510:
}
}
}
}
}</lang>
}</syntaxhighlight>
In a C# application with a reference to System.Windows.Forms, the following can be used to retrieve the executable name and arguments without the full path.
In a C# application with a reference to System.Windows.Forms, the following can be used to retrieve the executable name and arguments without the full path.
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
namespace ProgramName
namespace ProgramName
{
{
Line 459: Line 530:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
C++ has difficulty accessing source code filenames, because C code must be compiled into an executable. However, C++ can access the executable's filename.
C++ can access the executable's filename through the arguments to main().


<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>


using namespace std;
using namespace std;
Line 471: Line 542:
char *program = argv[0];
char *program = argv[0];
cout << "Program: " << program << endl;
cout << "Program: " << program << endl;
}</syntaxhighlight>

return 0;
}</lang>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>":";exec lein exec $0 ${1+"$@"}
<syntaxhighlight lang="clojure">":";exec lein exec $0 ${1+"$@"}
":";exit
":";exit


Line 487: Line 556:


(when (.contains (first *command-line-args*) *source-path*)
(when (.contains (first *command-line-args*) *source-path*)
(apply -main (rest *command-line-args*)))</lang>
(apply -main (rest *command-line-args*)))</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
Line 493: Line 562:
COBOL has an internal PROGRAM-ID name, and then the external invocation name.
COBOL has an internal PROGRAM-ID name, and then the external invocation name.


<lang COBOL> identification division.
<syntaxhighlight lang="cobol"> identification division.
program-id. sample.
program-id. sample.


Line 510: Line 579:


goback.
goback.
end program sample.</lang>
end program sample.</syntaxhighlight>


{{out}}
{{out}}
Line 519: Line 588:
=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
scriptname.coffee:
scriptname.coffee:
<lang coffeescript>#!/usr/bin/env coffee
<syntaxhighlight lang="coffeescript">#!/usr/bin/env coffee


main = () ->
main = () ->
Line 525: Line 594:
console.log "Program: " + program
console.log "Program: " + program


if not module.parent then main()</lang>
if not module.parent then main()</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Shebangs require a special tweak to ~/.clisprc.lisp.
Shebangs require a special tweak to ~/.clisprc.lisp.


<lang lisp>;;; Play nice with shebangs
<syntaxhighlight lang="lisp">;;; Play nice with shebangs
(set-dispatch-macro-character #\# #\!
(set-dispatch-macro-character #\# #\!
(lambda (stream character n)
(lambda (stream character n)
(declare (ignore character n))
(declare (ignore character n))
(read-line stream nil nil t)
(read-line stream nil nil t)
nil))</lang>
nil))</syntaxhighlight>


<lang lisp>#!/bin/sh
<syntaxhighlight lang="lisp">#!/bin/sh
#|
#|
exec clisp -q -q $0 $0 ${1+"$@"}
exec clisp -q -q $0 $0 ${1+"$@"}
Line 566: Line 635:
args
args
:test #'(lambda (x y) (search x y :test #'equalp)))
:test #'(lambda (x y) (search x y :test #'equalp)))
(main args)))</lang>
(main args)))</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<lang d>#!/usr/bin/env rdmd
<syntaxhighlight lang="d">#!/usr/bin/env rdmd


import std.stdio;
import std.stdio;
Line 575: Line 644:
void main(in string[] args) {
void main(in string[] args) {
writeln("Program: ", args[0]);
writeln("Program: ", args[0]);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>C:\rosetta>program_name.exe
<pre>C:\rosetta>program_name.exe
Program: program_name.exe</pre>
Program: program_name.exe</pre>


<lang sh>$ dmd scriptname.d
<syntaxhighlight lang="sh">$ dmd scriptname.d
$ ./scriptname
$ ./scriptname
Program: ./scriptname</lang>
Program: ./scriptname</syntaxhighlight>


If the system is configured, the D programming language offers an 'interpreted-looking' mode, which exhibits slightly different behavior than the normal compilation:
If the system is configured, the D programming language offers an 'interpreted-looking' mode, which exhibits slightly different behavior than the normal compilation:
<lang sh>$ ./scriptname.d
<syntaxhighlight lang="sh">$ ./scriptname.d
Program: /tmp/.rdmd/Users/andrew/Desktop/src/scriptname/scriptname.d.D3B32385A31B968A3CF8CAF1E1426E5F</lang>
Program: /tmp/.rdmd/Users/andrew/Desktop/src/scriptname/scriptname.d.D3B32385A31B968A3CF8CAF1E1426E5F</syntaxhighlight>




Alternative method using built-in function [http://dlang.org/changelog.html#current_path thisExePath()]
Alternative method using built-in function [http://dlang.org/changelog.html#current_path thisExePath()]
{{works with|D|2.064+}}
{{works with|D|2.064+}}
<lang d>// thisExePath function was introduced in D 2.064 (November 5, 2013)
<syntaxhighlight lang="d">// thisExePath function was introduced in D 2.064 (November 5, 2013)


import std.file;
import std.file;
Line 599: Line 668:
{
{
writeln("Program: ", thisExePath());
writeln("Program: ", thisExePath());
}</lang>
}</syntaxhighlight>
{{out}} <pre>Z:\rosettacode>program_name.exe
{{out}} <pre>Z:\rosettacode>program_name.exe
Program: Z:\rosettacode\program_name.exe</pre>
Program: Z:\rosettacode\program_name.exe</pre>


=={{header|Dart}}==
=={{header|Dart}}==
<lang dart>#!/usr/bin/env dart
<syntaxhighlight lang="dart">#!/usr/bin/env dart


main() {
main() {
var program = new Options().script;
var program = new Options().script;
print("Program: ${program}");
print("Program: ${program}");
}</lang>
}</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang Delphi>program ProgramName;
<syntaxhighlight lang="delphi">program ProgramName;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 619: Line 688:
Writeln('Program name: ' + ParamStr(0));
Writeln('Program name: ' + ParamStr(0));
Writeln('Command line: ' + CmdLine);
Writeln('Command line: ' + CmdLine);
end.</lang>
end.</syntaxhighlight>


=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==


<lang dejavu>!print( "Name of this file: " get-from !args 0 )</lang>
<syntaxhighlight lang="dejavu">!print( "Name of this file: " get-from !args 0 )</syntaxhighlight>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang lisp>
<syntaxhighlight lang="lisp">
(js-eval "window.location.href")
(js-eval "window.location.href")
→ "http://www.echolalie.org/echolisp/"
→ "http://www.echolalie.org/echolisp/"
</syntaxhighlight>
</lang>


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.x :
ELENA 4.x :
<lang elena>import extensions;
<syntaxhighlight lang="elena">import extensions;
public program()
public program()
Line 640: Line 709:
console.printLine(program_arguments[0]); // the program name
console.printLine(program_arguments[0]); // the program name
}</lang>
}</syntaxhighlight>


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<lang lisp>:;exec emacs -batch -l $0 -f main $*
<syntaxhighlight lang="lisp">:;exec emacs -batch -l $0 -f main $*


;;; Shebang from John Swaby
;;; Shebang from John Swaby
Line 649: Line 718:


(defun main ()
(defun main ()
(let ((program (nth 2 command-line-args)))
(let ((program (nth 2 command-line-args)))
(message "Program: %s" program)))</lang>
(message "Program: %s" program)))</syntaxhighlight>


<code>load-file-name</code> is the ".el" or ".elc" currently being loaded. Within a batch <code>-l</code> it will be the script name, but within sub-loads like <code>require</code> etc it is that sub-load.
<code>load-file-name</code> is the ".el" or ".elc" currently being loaded. Within a batch <code>-l</code> it will be the script name, but within sub-loads like <code>require</code> etc it is that sub-load.

=={{header|EMal}}==
<syntaxhighlight lang="emal">
writeLine("path: " + Runtime.path)
writeLine("name: " + Runtime.name)
writeLine("args: " + Runtime.args)
</syntaxhighlight>
{{out}}
<pre>
emal.exe Org\RosettaCode\ProgramName.emal sample arguments
path: C:\tmp\Org\RosettaCode\ProgramName.emal
name: ProgramName.emal
args: [sample,arguments]
</pre>


=={{header|Erlang}}==
=={{header|Erlang}}==
Line 658: Line 741:
When compiled Erlang's macros hold information about the running module.
When compiled Erlang's macros hold information about the running module.


<lang erlang>%% Compile
<syntaxhighlight lang="erlang">%% Compile
%%
%%
%% erlc scriptname.erl
%% erlc scriptname.erl
Line 672: Line 755:
Program = ?FILE,
Program = ?FILE,
io:format("Program: ~s~n", [Program]),
io:format("Program: ~s~n", [Program]),
init:stop().</lang>
init:stop().</syntaxhighlight>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>constant cmd = command_line()
<syntaxhighlight lang="euphoria">constant cmd = command_line()
puts(1,cmd[2])</lang>
puts(1,cmd[2])</syntaxhighlight>


=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
Line 686: Line 769:
* Run as a dotslashed program in Unix (./scriptname.fsx)
* Run as a dotslashed program in Unix (./scriptname.fsx)


<lang fsharp>#light (*
<syntaxhighlight lang="fsharp">#light (*
exec fsharpi --exec $0 --quiet
exec fsharpi --exec $0 --quiet
*)
*)
Line 705: Line 788:


let main =
let main =
printfn "%s" scriptname</lang>
printfn "%s" scriptname</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==


<lang factor>#! /usr/bin/env factor
<syntaxhighlight lang="factor">#! /usr/bin/env factor
USING: namespaces io command-line ;
USING: namespaces io command-line ;
Line 716: Line 799:
: main ( -- ) script get print ;
: main ( -- ) script get print ;
MAIN: main</lang>
MAIN: main</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
{{works with|GNU Forth}}
{{works with|GNU Forth}}
<lang forth>0 arg type cr \ gforth or gforth-fast, for example
<syntaxhighlight lang="forth">0 arg type cr \ gforth or gforth-fast, for example
1 arg type cr \ name of script</lang>
1 arg type cr \ name of script</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
Please find example runs in the comments at the beginning of the FORTRAN2003 source. Program name verification can deter system attackers. Therefore, the code is provided as a separate easily reused module.
Please find example runs in the comments at the beginning of the FORTRAN2003 source. Program name verification can deter system attackers. Therefore, the code is provided as a separate easily reused module.
<syntaxhighlight lang="fortran">
<lang FORTRAN>
! program run with invalid name path/f
! program run with invalid name path/f
!
!
Line 773: Line 856:
write(6,*)'program continues...'
write(6,*)'program continues...'
end program name
end program name
</syntaxhighlight>
</lang>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Print "The program was invoked like this => "; Command(0) + " " + Command(-1)
Print "The program was invoked like this => "; Command(0) + " " + Command(-1)
Print "Press any key to quit"
Print "Press any key to quit"
Sleep</lang>
Sleep</syntaxhighlight>


=={{header|FutureBasic}}==
There are several ways to retrieve the program name. These functions return a string containing the name that can be used in various ways.
<syntaxhighlight lang="futurebasic">
print fn ProcessInfoProcessName
print fn RunningApplicationLocalizedName( fn RunningApplicationCurrentApplication )
</syntaxhighlight>


=={{header|Gambas}}==
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=fc8af45b13a9bb52b6955bab487fc7ac Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=fc8af45b13a9bb52b6955bab487fc7ac Click this link to run this code]'''
<lang gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()
Dim sTemp As String
Dim sTemp As String


Line 793: Line 884:
Next
Next


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 800: Line 891:


=={{header|Genie}}==
=={{header|Genie}}==
<lang genie>[indent=4]
<syntaxhighlight lang="genie">[indent=4]
init
init
print args[0]
print args[0]
print Path.get_basename(args[0])
print Path.get_basename(args[0])
print Environment.get_application_name()
print Environment.get_application_name()
print Environment.get_prgname()</lang>
print Environment.get_prgname()</syntaxhighlight>


{{out}}
{{out}}
Line 818: Line 909:
scriptname.go:
scriptname.go:


<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 827: Line 918:
func main() {
func main() {
fmt.Println("Program:", os.Args[0])
fmt.Println("Program:", os.Args[0])
}</lang>
}</syntaxhighlight>
{{out|Command line session}}
{{out|Command line session}}
<pre>
<pre>
Line 843: Line 934:
If you want the script filename, use:
If you want the script filename, use:


<lang groovy>#!/usr/bin/env groovy
<syntaxhighlight lang="groovy">#!/usr/bin/env groovy


def program = getClass().protectionDomain.codeSource.location.path
def program = getClass().protectionDomain.codeSource.location.path


println "Program: " + program</lang>
println "Program: " + program</syntaxhighlight>


But if you just want the class name, there are easier ways.
But if you just want the class name, there are easier ways.


So, just typing in and running the following in the GroovyConsole environment:
So, just typing in and running the following in the GroovyConsole environment:
<lang groovy>println this.class.getName()</lang>
<syntaxhighlight lang="groovy">println this.class.getName()</syntaxhighlight>
yields the following on the first run:
yields the following on the first run:
<pre>ConsoleScript0</pre>
<pre>ConsoleScript0</pre>
Line 866: Line 957:
Haskell has an impure function for this.
Haskell has an impure function for this.


<lang haskell>import System (getProgName)
<syntaxhighlight lang="haskell">import System (getProgName)


main :: IO ()
main :: IO ()
main = getProgName >>= putStrLn . ("Program: " ++)</lang>
main = getProgName >>= putStrLn . ("Program: " ++)</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
write(&progname) # obtain and write out the program name from the keyword &progname
write(&progname) # obtain and write out the program name from the keyword &progname
end</lang>
end</syntaxhighlight>


=={{header|Io}}==
=={{header|Io}}==
<lang io>#!/usr/bin/env io
<syntaxhighlight lang="io">#!/usr/bin/env io


main := method(
main := method(
Line 885: Line 976:
)
)


if (System args size > 0 and System args at(0) containsSeq("scriptname"), main)</lang>
if (System args size > 0 and System args at(0) containsSeq("scriptname"), main)</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==


<lang j>#!/usr/bin/env jconsole
<syntaxhighlight lang="j">#!/usr/bin/env jconsole


program =: monad : 0
program =: monad : 0
Line 901: Line 992:
echo 'Program: ', program 0
echo 'Program: ', program 0


exit ''</lang>
exit ''</syntaxhighlight>

=={{header|Jakt}}==
The name of the program is stored in the first index of the array passed to main. This is the name of the compiled executable, so when using jakt -cr the value will be a path starting with build/.

<syntaxhighlight lang="jakt">
fn main(arguments: [String]) {
let program_name = arguments[0]
println("{}", program_name)
}
</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
Line 910: Line 1,011:


You can get the listing of the arguments to the <code>java</code> command through a system property. The first one is the name of the main class that was run. This depends on a system property named "sun.java.command", which might not exist on all Java virtual machines.
You can get the listing of the arguments to the <code>java</code> command through a system property. The first one is the name of the main class that was run. This depends on a system property named "sun.java.command", which might not exist on all Java virtual machines.
<lang java>public class ScriptName {
<syntaxhighlight lang="java">public class ScriptName {
public static void main(String[] args) {
public static void main(String[] args) {
String program = System.getProperty("sun.java.command").split(" ")[0];
String program = System.getProperty("sun.java.command").split(" ")[0];
System.out.println("Program: " + program);
System.out.println("Program: " + program);
}
}
}</lang>
}</syntaxhighlight>


An alternate solution is to create a dummy inner class, and then retrieve its enclosing class (which is the class the main method is in) through reflection (though this will not work if the code is placed in a method in another source file--it will give the name of the class it is in inside that source file):
An alternate solution is to create a dummy inner class, and then retrieve its enclosing class (which is the class the main method is in) through reflection (though this will not work if the code is placed in a method in another source file--it will give the name of the class it is in inside that source file):
<lang java>public class ScriptName {
<syntaxhighlight lang="java">public class ScriptName {
public static void main(String[] args) {
public static void main(String[] args) {
Class c = new Object(){}.getClass().getEnclosingClass();
Class c = new Object(){}.getClass().getEnclosingClass();
System.out.println("Program: " + c.getName());
System.out.println("Program: " + c.getName());
}
}
}</lang>
}</syntaxhighlight>


A solution using the security manager:
A solution using the security manager:
<lang java>public class ScriptName {
<syntaxhighlight lang="java">public class ScriptName {
public static void main(String[] args) {
public static void main(String[] args) {
Class c = System.getSecurityManager().getClassContext()[0];
Class c = System.getSecurityManager().getClassContext()[0];
System.out.println("Program: " + c.getName());
System.out.println("Program: " + c.getName());
}
}
}</lang>
}</syntaxhighlight>


A solution using the stack trace (requires Java 1.5+):
A solution using the stack trace (requires Java 1.5+):
<lang java>public class ScriptName {
<syntaxhighlight lang="java">public class ScriptName {
public static void main(String[] args) {
public static void main(String[] args) {
String program = Thread.currentThread().getStackTrace()[1].getClassName();
String program = Thread.currentThread().getStackTrace()[1].getClassName();
System.out.println("Program: " + program);
System.out.println("Program: " + program);
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
{{incorrect|JavaScript|Program name, not function name. Show sample output.}}

<small><i>Suggestion: document.location.href is probably closer to task requirements (and better than a script name), plus arguments.callee.name is long dead. --[[User:Petelomax|Pete Lomax]] ([[User talk:Petelomax|talk]]) 23:29, 24 March 2022 (UTC)</i></small><br>
There is no capability within the ECMA-262 standard (the standard for ECMAScript, the language underlying JavaScript) for a function to determine its name. Since objects in JavaScript are first class objects, variables and properties are only references to objects. The name of an object might be said to be the name used to reference it, however a single object may have many variables and properties that reference it, or none.
There is no capability within the ECMA-262 standard (the standard for ECMAScript, the language underlying JavaScript) for a function to determine its name. Since objects in JavaScript are first class objects, variables and properties are only references to objects. The name of an object might be said to be the name used to reference it, however a single object may have many variables and properties that reference it, or none.


In some implementations, the following (non–standard) code will work:
In some implementations, the following (non–standard) code will work:


<lang javascript>function foo() {
<syntaxhighlight lang="javascript">function foo() {
return arguments.callee.name;
return arguments.callee.name;
}</lang>
}</syntaxhighlight>


But it will fail in in others. JavaScript also has anonymous functions that don't have a name, e.g.:
But it will fail in in others. JavaScript also has anonymous functions that don't have a name, e.g.:
<lang javascript>(function(){alert(arguments.callee.name);}())</lang>
<syntaxhighlight lang="javascript">(function(){alert(arguments.callee.name);}())</syntaxhighlight>
returns an empty string or <code>undefined</code> even where the first example works.
returns an empty string or <code>undefined</code> even where the first example works.


Line 958: Line 1,060:
Node.js has a global variable for this.
Node.js has a global variable for this.


<lang javascript>#!/usr/bin/env node
<syntaxhighlight lang="javascript">#!/usr/bin/env node
/*jslint nodejs:true */
/*jslint nodejs:true */


Line 966: Line 1,068:
}
}


if (!module.parent) { main(); }</lang>
if (!module.parent) { main(); }</syntaxhighlight>

=={{header|Joy}}==
<syntaxhighlight lang="joy">#!/usr/bin/joy

argv first putchars.</syntaxhighlight>


=={{header|Jsish}}==
=={{header|Jsish}}==
<lang javascript>#!/usr/bin/env jsish
<syntaxhighlight lang="javascript">#!/usr/bin/env jsish
/* Program name, in Jsish */
/* Program name, in Jsish */
puts('Executable:', Info.executable());
puts('Executable:', Info.executable());
puts('Argv0 :', Info.argv0());</lang>
puts('Argv0 :', Info.argv0());</syntaxhighlight>


{{out}}
{{out}}
Line 981: Line 1,088:
=={{header|Julia}}==
=={{header|Julia}}==
Julia strips the program file name from <tt>ARGS</tt>, so this information is not available to the program from its command line arguments. Instead it is accessible via <tt>Base.source_path()</tt>.
Julia strips the program file name from <tt>ARGS</tt>, so this information is not available to the program from its command line arguments. Instead it is accessible via <tt>Base.source_path()</tt>.
<syntaxhighlight lang="julia">
<lang Julia>
prog = basename(Base.source_path())
prog = basename(Base.source_path())
println("This program file is \"", prog, "\".")
println("This program file is \"", prog, "\".")
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 992: Line 1,099:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


// 'progname.kt' packaged as 'progname.jar'
// 'progname.kt' packaged as 'progname.jar'
Line 999: Line 1,106:
println(System.getProperty("sun.java.command")) // may not exist on all JVMs
println(System.getProperty("sun.java.command")) // may not exist on all JVMs
println(System.getProperty("java.vm.name"))
println(System.getProperty("java.vm.name"))
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,009: Line 1,116:
=={{header|langur}}==
=={{header|langur}}==
The script name is in the _script variable (separate from the arguments, in the _args variable).
The script name is in the _script variable (separate from the arguments, in the _args variable).
<lang langur>writeln "script: ", _script
<syntaxhighlight lang="langur">writeln "script: ", _script
writeln "script args: ", _args
writeln "script args: ", _args</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,018: Line 1,124:


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang lasso>#!/usr/bin/lasso9
<syntaxhighlight lang="lasso">#!/usr/bin/lasso9


stdoutnl("Program: " + $argv->first)</lang>
stdoutnl("Program: " + $argv->first)</syntaxhighlight>
Output:
Output:
<lang shell>$ lasso9 script_name.lasso
<syntaxhighlight lang="shell">$ lasso9 script_name.lasso
Program: script_name.lasso</lang>
Program: script_name.lasso</syntaxhighlight>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
nSize = _MAX_PATH + 2
nSize = _MAX_PATH + 2
lpFilename$ = space$(nSize); chr$(0)
lpFilename$ = space$(nSize); chr$(0)
Line 1,069: Line 1,175:
end function
end function


</syntaxhighlight>
</lang>
Output:
Output:
<lang text>
<syntaxhighlight lang="text">
Path to LB exe
Path to LB exe
C:\progs\Liberty BASIC v4.04\liberty.exe
C:\progs\Liberty BASIC v4.04\liberty.exe
current program file (:last one on LRU list)
current program file (:last one on LRU list)
C:\progs\Liberty BASIC v4.04\untitled.bas
C:\progs\Liberty BASIC v4.04\untitled.bas
</syntaxhighlight>
</lang>


=={{header|Lingo}}==
=={{header|Lingo}}==
<lang lingo>put _player.applicationName
<syntaxhighlight lang="lingo">put _player.applicationName
-- "lsw.exe"
-- "lsw.exe"
put _movie.name
put _movie.name
-- "lsw_win_d11.dir"</lang>
-- "lsw_win_d11.dir"</syntaxhighlight>


=={{header|LLVM}}==
=={{header|LLVM}}==
Like C, LLVM can use argv to access the executable's filename.
Like C, LLVM can use argv to access the executable's filename.


<lang sh>$ make
<syntaxhighlight lang="sh">$ make
llvm-as scriptname.ll
llvm-as scriptname.ll
llc -disable-cfi scriptname.bc
llc -disable-cfi scriptname.bc
gcc -o scriptname scriptname.s
gcc -o scriptname scriptname.s
./scriptname
./scriptname
Program: ./scriptname</lang>
Program: ./scriptname</syntaxhighlight>


Makefile
Makefile




<lang make>all: scriptname.ll
<syntaxhighlight lang="make">all: scriptname.ll
llvm-as scriptname.ll
llvm-as scriptname.ll
llc scriptname.bc
llc scriptname.bc
Line 1,106: Line 1,212:
-rm scriptname
-rm scriptname
-rm scriptname.s
-rm scriptname.s
-rm scriptname.bc</lang>
-rm scriptname.bc</syntaxhighlight>


<lang llvm>@msg_main = internal constant [13 x i8] c"Program: %s\0A\00"
<syntaxhighlight lang="llvm">@msg_main = internal constant [13 x i8] c"Program: %s\0A\00"


declare i32 @printf(i8* noalias nocapture, ...)
declare i32 @printf(i8* noalias nocapture, ...)
Line 1,117: Line 1,223:


ret i32 0
ret i32 0
}</lang>
}</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
Lua's arg is like C's argv.
Lua's arg is like C's argv.


<lang lua>#!/usr/bin/env lua
<syntaxhighlight lang="lua">#!/usr/bin/env lua


function main(arg)
function main(arg)
Line 1,133: Line 1,239:
else
else
module(..., package.seeall)
module(..., package.seeall)
end</lang>
end</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Module Checkit {
Declare GetModuleFileName Lib "kernel32.GetModuleFileNameW" {Long hModule, &lpFileName$, Long nSize}
Declare GetModuleFileName Lib "kernel32.GetModuleFileNameW" {Long hModule, &lpFileName$, Long nSize}
Line 1,154: Line 1,260:
}
}
SayIt
SayIt
</syntaxhighlight>
</lang>


=={{header|Make}}==
=={{header|Make}}==


<lang make>NAME=$(CURDIR)/$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))
<syntaxhighlight lang="make">NAME=$(CURDIR)/$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))


all:
all:
@echo $(NAME)
@echo $(NAME)
</syntaxhighlight>
</lang>

=={{header|Mathematica}}==

<lang mathematica>#!/usr/bin/env MathKernel -script


=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">#!/usr/bin/env MathKernel -script
ScriptName[] = Piecewise[
ScriptName[] = Piecewise[
{
{
Line 1,174: Line 1,278:
$CommandLine[[Position[$CommandLine, "-script", 1][[1,1]] + 1]]
$CommandLine[[Position[$CommandLine, "-script", 1][[1,1]] + 1]]
]
]

Program = ScriptName[];
Program = ScriptName[];
Print["Program: " <> Program]</syntaxhighlight>

Print["Program: " <> Program]</lang>


=={{header|Mercury}}==
=={{header|Mercury}}==


<lang mercury>:- module program_name.
<syntaxhighlight lang="mercury">:- module program_name.
:- interface.
:- interface.


Line 1,196: Line 1,298:
io.print_line(ProgName, !IO).
io.print_line(ProgName, !IO).


:- end_module program_name.</lang>
:- end_module program_name.</syntaxhighlight>


=={{header|Mozart/Oz}}==
=={{header|Mozart/Oz}}==


Makefile:
Makefile:
<lang make>all: test
<syntaxhighlight lang="make">all: test


test: scriptname
test: scriptname
Line 1,211: Line 1,313:
clean:
clean:
-rm scriptname
-rm scriptname
-rm *.exe</lang>
-rm *.exe</syntaxhighlight>


scriptname.oz:
scriptname.oz:
<lang oz>functor
<syntaxhighlight lang="oz">functor
import
import
System
System
Line 1,225: Line 1,327:
end
end
end
end
</syntaxhighlight>
</lang>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<lang Nanoquery>println args[1]</lang>
<syntaxhighlight lang="nanoquery">println args[1]</syntaxhighlight>
{{out}}
{{out}}
<pre>programname.nq</pre>
<pre>programname.nq</pre>


=={{header|Nemerle}}==
=={{header|Nemerle}}==
<lang Nemerle>using System.Environment;
<syntaxhighlight lang="nemerle">using System.Environment;
...
...
def program_name = GetCommandLineArgs()[0];
def program_name = GetCommandLineArgs()[0];
...</lang>
...</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 1,247: Line 1,349:
say 'Program:' System.getProperty('sun.java.command')
say 'Program:' System.getProperty('sun.java.command')
return
return
</syntaxhighlight>
</lang>
'''Output'''
'''Output'''


Line 1,267: Line 1,369:
newLISP has a function, (main-args int) for this.
newLISP has a function, (main-args int) for this.


<lang lisp>#!/usr/bin/env newlisp
<syntaxhighlight lang="lisp">#!/usr/bin/env newlisp


(let ((program (main-args 1)))
(let ((program (main-args 1)))
(println (format "Program: %s" program))
(println (format "Program: %s" program))
(exit))</lang>
(exit))</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import os
<syntaxhighlight lang="nim">import os
echo getAppFilename() # Prints the full path of the executed file
echo getAppFilename() # Prints the full path of the executed file
echo paramStr(0) # Prints argv[0]</lang>
echo paramStr(0) # Prints argv[0]</syntaxhighlight>


=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
Works with oo2c Version 2
Works with oo2c Version 2
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE ProgramName;
MODULE ProgramName;
IMPORT
IMPORT
Line 1,288: Line 1,390:
Out.Object("Program name: " + Args.Get(0));Out.Ln
Out.Object("Program name: " + Args.Get(0));Out.Ln
END ProgramName.
END ProgramName.
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,298: Line 1,400:
scriptname.m:
scriptname.m:


<lang objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>


int main(int argc, char **argv) {
int main(int argc, char **argv) {
Line 1,313: Line 1,415:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


<lang sh>$ gcc -o scriptname -framework foundation scriptname.m
<syntaxhighlight lang="sh">$ gcc -o scriptname -framework foundation scriptname.m
$ ./scriptname
$ ./scriptname
Program: ./scriptname</lang>
Program: ./scriptname</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==


<lang ocaml>let () =
<syntaxhighlight lang="ocaml">let () =
print_endline Sys.executable_name;
print_endline Sys.executable_name;
print_endline Sys.argv.(0)</lang>
print_endline Sys.argv.(0)</syntaxhighlight>


<pre>
<pre>
Line 1,343: Line 1,445:


=={{header|Octave}}==
=={{header|Octave}}==
<lang octave>function main()
<syntaxhighlight lang="octave">function main()
program = program_name();
program = program_name();
printf("Program: %s", program);
printf("Program: %s", program);
endfunction
endfunction


main();</lang>
main();</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
First argument of *vm-args* is an executing program name.
First argument of *vm-args* is an executing program name.
<lang scheme>
<syntaxhighlight lang="scheme">
(print (car *vm-args*))
(print (car *vm-args*))
</syntaxhighlight>
</lang>


=={{header|Order}}==
=={{header|Order}}==
This is relatively trivial in Order, as the program being executed is a macro expression in the current C program file being read by the compiler:
This is relatively trivial in Order, as the program being executed is a macro expression in the current C program file being read by the compiler:
<lang c>__FILE__</lang>
<syntaxhighlight lang="c">__FILE__</syntaxhighlight>
When including another file containing another <code>ORDER_PP</code> expression, within that file the <code>__FILE__</code> macro will expand to the name of that file; but arguably that expression constitutes a separate Order program within the greater C project.
When including another file containing another <code>ORDER_PP</code> expression, within that file the <code>__FILE__</code> macro will expand to the name of that file; but arguably that expression constitutes a separate Order program within the greater C project.


Line 1,366: Line 1,468:
=={{header|Pascal}}==
=={{header|Pascal}}==


<lang pascal>program ScriptName;
<syntaxhighlight lang="pascal">program ScriptName;
var
var
prog : String;
prog : String;
Line 1,373: Line 1,475:
write('Program: ');
write('Program: ');
writeln(prog)
writeln(prog)
end.</lang>
end.</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>#!/usr/bin/env perl
<syntaxhighlight lang="perl">#!/usr/bin/env perl


use strict;
use strict;
Line 1,386: Line 1,488:
}
}


unless(caller) { main; }</lang>
unless(caller) { main; }</syntaxhighlight>


<code>$0</code> includes the full path if a script is run as say <code>perl /some/dir/foo.pl</code>. The <code>FindBin</code> module can give just the basename. This can be good for printing in diagnostics etc.
<code>$0</code> includes the full path if a script is run as say <code>perl /some/dir/foo.pl</code>. The <code>FindBin</code> module can give just the basename. This can be good for printing in diagnostics etc.
<lang Perl>use FindBin;
<syntaxhighlight lang="perl">use FindBin;
print "Program name $FindBin::Script\n";</lang>
print "Program name $FindBin::Script\n";</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>puts(1,command_line()[2])</lang>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">cl2</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">command_line</span><span style="color: #0000FF;">()[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">cl2</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- full path</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s\n"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">get_file_name</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cl2</span><span style="color: #0000FF;">))</span> <span style="color: #000080;font-style:italic;">-- eg test.exw or test.exe or test.htm</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s\n"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">get_file_base</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cl2</span><span style="color: #0000FF;">))</span> <span style="color: #000080;font-style:italic;">-- eg test</span>
<!--</syntaxhighlight>-->

=={{header|Phixmonti}}==
<syntaxhighlight lang="phixmonti">argument 1 get ?</syntaxhighlight>


=={{header|PHP}}==
=={{header|PHP}}==
PHP has a global dictionary for this.
PHP has a global dictionary for this.


<lang php><?php
<syntaxhighlight lang="php"><?php
$program = $_SERVER["SCRIPT_NAME"];
$program = $_SERVER["SCRIPT_NAME"];
echo "Program: $program\n";
echo "Program: $program\n";
?></lang>
?></syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
The function '[http://software-lab.de/doc/refC.html#cmd cmd]' returns the command name.
The function '[http://software-lab.de/doc/refC.html#cmd cmd]' returns the command name.
<lang PicoLisp>: (cmd)
<syntaxhighlight lang="picolisp">: (cmd)
-> "/usr/bin/picolisp"</lang>
-> "/usr/bin/picolisp"</syntaxhighlight>


=={{header|PowerBASIC}}==
=={{header|PowerBASIC}}==
Line 1,412: Line 1,523:
Previous versions of PowerBASIC ([[PB/Win]] 8 or older; [[PB/CC]] 4 or older) have to make an [[API]] call:
Previous versions of PowerBASIC ([[PB/Win]] 8 or older; [[PB/CC]] 4 or older) have to make an [[API]] call:


<lang powerbasic>#INCLUDE "Win32API.inc"
<syntaxhighlight lang="powerbasic">#INCLUDE "Win32API.inc"
'[...]
'[...]
DIM fullpath AS ASCIIZ * 260, appname AS STRING
DIM fullpath AS ASCIIZ * 260, appname AS STRING
Line 1,420: Line 1,531:
ELSE
ELSE
appname = fullpath
appname = fullpath
END IF</lang>
END IF</syntaxhighlight>


{{works with|PowerBASIC for Windows|9}}
{{works with|PowerBASIC for Windows|9}}
Line 1,426: Line 1,537:


Recent versions of PowerBASIC provide the <code>EXE</code> object; <code>EXE.NAME$</code> returns the program's name, while <code>EXE.NAMEX$</code> returns the program's name and extension. (<code>EXE.EXTN$</code> returns the extension only.) So, to get the program's name, we do this:
Recent versions of PowerBASIC provide the <code>EXE</code> object; <code>EXE.NAME$</code> returns the program's name, while <code>EXE.NAMEX$</code> returns the program's name and extension. (<code>EXE.EXTN$</code> returns the extension only.) So, to get the program's name, we do this:
<lang powerbasic>appname = EXE.NAMEX$</lang>
<syntaxhighlight lang="powerbasic">appname = EXE.NAMEX$</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
# write this in file <program.ps1>
# write this in file <program.ps1>
$MyInvocation.MyCommand.Name
$MyInvocation.MyCommand.Name
# launch with <.\program>
# launch with <.\program>
</syntaxhighlight>
</lang>
<b>Output:</b>
<b>Output:</b>
<pre>
<pre>
Line 1,440: Line 1,551:


=={{header|Prolog}}==
=={{header|Prolog}}==
<lang Prolog>% SWI-Prolog version 8.0.0 for i686-linux.
<syntaxhighlight lang="prolog">% SWI-Prolog version 8.0.0 for i686-linux.
% This will find itself, and return the knowledge base it is in.
% This will find itself, and return the knowledge base it is in.
file_name(F) :- true
file_name(F) :- true
Line 1,447: Line 1,558:
, source_file(M:P, F) % F is the file .
, source_file(M:P, F) % F is the file .
, \+ predicate_property(M:P, imported_from(_))
, \+ predicate_property(M:P, imported_from(_))
.</lang>
.</syntaxhighlight>


Alternatively, you may prefer a list of all your knowledge bases; adding the following code to each of your knowledge bases will allow you to query <code>findall(F, source_file(this_is_one_of_my_files, F), L).</code>.
Alternatively, you may prefer a list of all your knowledge bases; adding the following code to each of your knowledge bases will allow you to query <code>findall(F, source_file(this_is_one_of_my_files, F), L).</code>.
<lang Prolog>:- multifile(this_is_one_of_my_files). this_is_one_of_my_files.</lang>
<syntaxhighlight lang="prolog">:- multifile(this_is_one_of_my_files). this_is_one_of_my_files.</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
PureBasic provides a way to retrieve the filename of the program being executed. It includes the file's path.
PureBasic provides a way to retrieve the filename of the program being executed. It includes the file's path.
<lang PureBasic>If OpenConsole()
<syntaxhighlight lang="purebasic">If OpenConsole()
PrintN(ProgramFilename())
PrintN(ProgramFilename())
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>
Sample output when executing the above program compiled to an executible file called 'program name.exe':
Sample output when executing the above program compiled to an executible file called 'program name.exe':
<pre>H:\Data\Rosetta Code\program name.exe</pre>
<pre>H:\Data\Rosetta Code\program name.exe</pre>
Line 1,466: Line 1,577:
Python has at least two ways to get the script name: the traditional ARGV and the inspect module.
Python has at least two ways to get the script name: the traditional ARGV and the inspect module.


<lang python>#!/usr/bin/env python
<syntaxhighlight lang="python">#!/usr/bin/env python


import sys
import sys
Line 1,475: Line 1,586:


if __name__ == "__main__":
if __name__ == "__main__":
main()</lang>
main()</syntaxhighlight>




<lang python>#!/usr/bin/env python
<syntaxhighlight lang="python">#!/usr/bin/env python


import inspect
import inspect
Line 1,487: Line 1,598:


if __name__ == "__main__":
if __name__ == "__main__":
main()</lang>
main()</syntaxhighlight>


=={{header|R}}==
=={{header|R}}==
R's syntax is complicated, but doable.
R's syntax is complicated, but doable.


<lang R>#!/usr/bin/env Rscript
<syntaxhighlight lang="r">#!/usr/bin/env Rscript


getProgram <- function(args) {
getProgram <- function(args) {
Line 1,503: Line 1,614:
cat("Program: ", program, "\n")
cat("Program: ", program, "\n")


q("no")</lang>
q("no")</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>#!/usr/bin/env racket
<syntaxhighlight lang="racket">#!/usr/bin/env racket
#lang racket
#lang racket


(define (program) (find-system-path 'run-file))
(define (program) (find-system-path 'run-file))


(module+ main (printf "Program: ~a\n" (program)))</lang>
(module+ main (printf "Program: ~a\n" (program)))</syntaxhighlight>


=={{header|Raku}}==
=={{header|Raku}}==
Line 1,517: Line 1,628:
{{works with|rakudo|2015-10-16}}
{{works with|rakudo|2015-10-16}}
In Raku, the name of the program being executed is in the special global variable <tt>$*PROGRAM-NAME</tt>.
In Raku, the name of the program being executed is in the special global variable <tt>$*PROGRAM-NAME</tt>.
<lang perl6>say $*PROGRAM-NAME;</lang>
<syntaxhighlight lang="raku" line>say $*PROGRAM-NAME;</syntaxhighlight>


=={{header|Raven}}==
=={{header|Raven}}==
<lang Raven>ARGS list " " join "%s\n" print</lang>
<syntaxhighlight lang="raven">ARGS list " " join "%s\n" print</syntaxhighlight>
{{out}}
{{out}}
<pre>raven arg_file.rv</pre>
<pre>raven arg_file.rv</pre>
Line 1,533: Line 1,644:
<br><br>It should be noted that the format of the complete path varies depending upon the operating system.
<br><br>It should be noted that the format of the complete path varies depending upon the operating system.


<lang REXX>/* Rexx */
<syntaxhighlight lang="rexx">/* Rexx */


Parse source . . pgmPath
Parse source . . pgmPath
Say pgmPath
Say pgmPath
</syntaxhighlight>
</lang>
;Output
;Output
<pre>
<pre>
Line 1,546: Line 1,657:
REXX does not support the use of arg(0) to access the program name. A workaround is to use a shell wrapper script to obtain and provide the invocation name of the wrapper:
REXX does not support the use of arg(0) to access the program name. A workaround is to use a shell wrapper script to obtain and provide the invocation name of the wrapper:


<lang sh>#!/bin/sh
<syntaxhighlight lang="sh">#!/bin/sh
rexxbit.rexx $0 $*</lang>
rexxbit.rexx $0 $*</syntaxhighlight>


Here is a rexx script that makes use of this:
Here is a rexx script that makes use of this:


<lang rexx>say "The program is called " arg(1)</lang>
<syntaxhighlight lang="rexx">say "The program is called " arg(1)</syntaxhighlight>


On TSO, this program
On TSO, this program
<lang rexx>/*REXX program RANG1 in PDS N561985.PRIV.CLIST W. Pachl */
<syntaxhighlight lang="rexx">/*REXX program RANG1 in PDS N561985.PRIV.CLIST W. Pachl */
Parse Source a b c
Parse Source a b c
Say 'a='a
Say 'a='a
Say 'b='!!b
Say 'b='!!b
Say 'c='c </lang>
Say 'c='c </syntaxhighlight>
yields
yields
<pre>
<pre>
Line 1,574: Line 1,685:
:::* ROO REXX
:::* ROO REXX
:::* ooRexx
:::* ooRexx
<lang rexx>/*REXX pgm displays the name (& possible path) of the REXX program name.*/
<syntaxhighlight lang="rexx">/*REXX pgm displays the name (& possible path) of the REXX program name.*/
parse version _version
parse version _version
parse source _system _howInvoked _path
parse source _system _howInvoked _path
Line 1,588: Line 1,699:
call prog_nam , 'subroutine' /*call ourself as a subroutine. */
call prog_nam , 'subroutine' /*call ourself as a subroutine. */
zz = prog_nam( , 'function') /* " " " " function. */
zz = prog_nam( , 'function') /* " " " " function. */
/*stick a fork in it, we're done.*/</lang>
/*stick a fork in it, we're done.*/</syntaxhighlight>
'''output''' &nbsp; when using '''BREXX''' with the input of: &nbsp; <tt> command </tt>
'''output''' &nbsp; when using '''BREXX''' with the input of: &nbsp; <tt> command </tt>
<pre>
<pre>
Line 1,688: Line 1,799:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
see "Active Source File Name : " + filename() + nl
see "Active Source File Name : " + filename() + nl
</syntaxhighlight>
</lang>
output
output
<lang ring>
<syntaxhighlight lang="ring">
Active Source File Name : tests\filename.ring
Active Source File Name : tests\filename.ring
</syntaxhighlight>
</lang>


Check the main file in the program
Check the main file in the program
<lang ring>
<syntaxhighlight lang="ring">
if sysargv[2] = filename()
if sysargv[2] = filename()
see "I'm the main program file!" + nl
see "I'm the main program file!" + nl
Line 1,704: Line 1,815:
see "I'm a sub file in a program" + nl
see "I'm a sub file in a program" + nl
ok
ok
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>#!/usr/bin/env ruby
<syntaxhighlight lang="ruby">#!/usr/bin/env ruby


puts "Path: #{$PROGRAM_NAME}" # or puts "Path: #{$0}"
puts "Path: #{$PROGRAM_NAME}" # or puts "Path: #{$0}"
puts "Name: #{File.basename $0}"</lang>
puts "Name: #{File.basename $0}"</syntaxhighlight>


For example,
For example,
Line 1,728: Line 1,839:
scriptname.rs:
scriptname.rs:


<lang rust>fn main() {
<syntaxhighlight lang="rust">fn main() {
println!("Program: {}", std::env::args().next().unwrap());
println!("Program: {}", std::env::args().next().unwrap());
}</lang>
}</syntaxhighlight>


Example:
Example:


<lang sh>$ rustc scriptname.rs
<syntaxhighlight lang="sh">$ rustc scriptname.rs
$ ./scriptname
$ ./scriptname
Program: ./scriptname</lang>
Program: ./scriptname</syntaxhighlight>


=={{header|SAC}}==
=={{header|SAC}}==
Line 1,742: Line 1,853:
scriptname.sac:
scriptname.sac:


<lang c>use StdIO: all;
<syntaxhighlight lang="c">use StdIO: all;
use Array: all;
use Array: all;
use String: { string };
use String: { string };
Line 1,751: Line 1,862:
printf("Program: %s\n", program);
printf("Program: %s\n", program);
return(0);
return(0);
}</lang>
}</syntaxhighlight>


Makefile:
Makefile:


<lang make>all: scriptname
<syntaxhighlight lang="make">all: scriptname


scriptname: scriptname.sac
scriptname: scriptname.sac
Line 1,762: Line 1,873:
clean:
clean:
-rm scriptname
-rm scriptname
-rm scriptname.c</lang>
-rm scriptname.c</syntaxhighlight>


Example:
Example:


<lang sh>$ make
<syntaxhighlight lang="sh">$ make
sac2c -o scriptname scriptname.sac
sac2c -o scriptname scriptname.sac
$ ./scriptname
$ ./scriptname
Program: ./scriptname</lang>
Program: ./scriptname</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>object ScriptName extends App {
<syntaxhighlight lang="scala">object ScriptName extends App {
println(s"Program of instantiated object: ${this.getClass.getName}")
println(s"Program of instantiated object: ${this.getClass.getName}")
// Not recommended, due various implementations
// Not recommended, due various implementations
println(s"Program via enviroment: ${System.getProperty("sun.java.command")}")
println(s"Program via enviroment: ${System.getProperty("sun.java.command")}")
}</lang>
}</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
Line 1,782: Line 1,893:
Getting the program name is tricky. When interpreted, the script name will be printed. When compiled, the executable name will be printed.
Getting the program name is tricky. When interpreted, the script name will be printed. When compiled, the executable name will be printed.


<lang scheme>#!/bin/sh
<syntaxhighlight lang="scheme">#!/bin/sh
#|
#|
exec csi -ss $0 ${1+"$@"}
exec csi -ss $0 ${1+"$@"}
Line 1,806: Line 1,917:


(if (equal? (car (program)) 'compiled)
(if (equal? (car (program)) 'compiled)
(main (cdr (argv))))</lang>
(main (cdr (argv))))</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
Line 1,813: Line 1,924:
When the program is compiled this is the path of the executable.
When the program is compiled this is the path of the executable.
The functions ''dir(PROGRAM)'' and ''file(PROGRAM)'' deliver the directory respectivly file name of the program path.
The functions ''dir(PROGRAM)'' and ''file(PROGRAM)'' deliver the directory respectivly file name of the program path.
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


const proc: main is func
const proc: main is func
Line 1,822: Line 1,933:
writeln("Program directory: " <& dir(PROGRAM));
writeln("Program directory: " <& dir(PROGRAM));
writeln("Program file: " <& file(PROGRAM));
writeln("Program file: " <& file(PROGRAM));
end func;</lang>
end func;</syntaxhighlight>


Output when the program is interpreted:
Output when the program is interpreted:
Line 1,839: Line 1,950:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>say __MAIN__;
<syntaxhighlight lang="ruby">say __MAIN__;
if (__MAIN__ != __FILE__) {
if (__MAIN__ != __FILE__) {
say "This file has been included!";
say "This file has been included!";
}</lang>
}</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
Line 1,849: Line 1,960:
Note that this only works when run as "./scriptname.st", because the shebang must force the script name onto ARGV.
Note that this only works when run as "./scriptname.st", because the shebang must force the script name onto ARGV.


<lang smalltalk>"exec" "gst" "-f" "$0" "$0" "$@"
<syntaxhighlight lang="smalltalk">"exec" "gst" "-f" "$0" "$0" "$@"
"exit"
"exit"


Line 1,856: Line 1,967:
program := Smalltalk getArgv: 1.
program := Smalltalk getArgv: 1.


Transcript show: 'Program: ', program; cr.</lang>
Transcript show: 'Program: ', program; cr.</syntaxhighlight>


{{works with|Smalltalk/X}}
{{works with|Smalltalk/X}}
Works when run in script mode or in a workspace.
Works when run in script mode or in a workspace.


<lang smalltalk>| program |
<syntaxhighlight lang="smalltalk">| program |


program := Smalltalk commandLine first.
program := Smalltalk commandLine first.
Transcript show: 'Program: ', program; cr.</lang>
Transcript show: 'Program: ', program; cr.</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>#!/usr/bin/env sml
<syntaxhighlight lang="sml">#!/usr/bin/env sml


let
let
Line 1,873: Line 1,984:
in
in
print ("Program: " ^ program ^ "\n")
print ("Program: " ^ program ^ "\n")
end;</lang>
end;</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>#!/usr/bin/env tclsh
<syntaxhighlight lang="tcl">#!/usr/bin/env tclsh


proc main {args} {
proc main {args} {
Line 1,885: Line 1,996:
if {$::argv0 eq [info script]} {
if {$::argv0 eq [info script]} {
main {*}$::argv
main {*}$::argv
}</lang>
}</syntaxhighlight>

=={{header|Transd}}==
<syntaxhighlight lang="Scheme">#lang transd

MainModule: {
_start: (λ
(textout (get @progArgs 0))
)
}</syntaxhighlight>


=={{header|TXR}}==
=={{header|TXR}}==
Line 1,891: Line 2,011:
Given this code in <code>program-name.txr</code>, marked executable:
Given this code in <code>program-name.txr</code>, marked executable:


<lang txr>#!/usr/local/bin/txr -B
<syntaxhighlight lang="txr">#!/usr/local/bin/txr -B
@(bind my-name @self-path)</lang>
@(bind my-name @self-path)</syntaxhighlight>


If we run it as an executable:
If we run it as an executable:
Line 1,917: Line 2,037:
=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|Bourne Shell}}
{{works with|Bourne Shell}}
<lang bash>#!/bin/sh
<syntaxhighlight lang="bash">#!/bin/sh


echo "Program: $0"</lang>
echo "Program: $0"</syntaxhighlight>


=={{header|Vala}}==
=={{header|Vala}}==
Get name of program and print to console:
Get name of program and print to console:
<lang vala>
<syntaxhighlight lang="vala">
public static void main(string[] args){
public static void main(string[] args){
string command_name = args[0];
string command_name = args[0];
Line 1,929: Line 2,049:
stdout.printf("%s\n", command_name);
stdout.printf("%s\n", command_name);
}
}
</syntaxhighlight>
</lang>


Output for program named "filename":
Output for program named "filename":
Line 1,939: Line 2,059:


VBA can retrieve the name of the program hosting the VBA code using the <code>Application</code> object:
VBA can retrieve the name of the program hosting the VBA code using the <code>Application</code> object:
<lang vb>Debug.Print Application.Name</lang>
<syntaxhighlight lang="vb">Debug.Print Application.Name</syntaxhighlight>


This is mostly useful for code that is shared between, say, [[wp:Microsoft Excel|Microsoft Excel]] and [[wp:Microsoft Word|Microsoft Word]], but has different requirements or actions depending on where it's running.
This is mostly useful for code that is shared between, say, [[wp:Microsoft Excel|Microsoft Excel]] and [[wp:Microsoft Word|Microsoft Word]], but has different requirements or actions depending on where it's running.
Line 1,949: Line 2,069:
vbscript provides the Wscript object. Among its properties are the following:
vbscript provides the Wscript object. Among its properties are the following:


<lang vbscript>
<syntaxhighlight lang="vbscript">
Wscript.Echo "FullName:",Wscript.FullName
Wscript.Echo "FullName:",Wscript.FullName
Wscript.Echo "Name:",Wscript.Name
Wscript.Echo "Name:",Wscript.Name
Line 1,955: Line 2,075:
Wscript.Echo "ScriptFullName:",Wscript.ScriptFullName
Wscript.Echo "ScriptFullName:",Wscript.ScriptFullName
Wscript.Echo "ScriptName:",Wscript.ScriptName
Wscript.Echo "ScriptName:",Wscript.ScriptName
</syntaxhighlight>
</lang>


<pre>
<pre>
Line 1,968: Line 2,088:


Visual Basic provides the <code>App</code> object, which has a property called <code>EXEName</code> that contains the program's filename ''without the extension''. (For most uses, this doesn't matter, but for code shared between, for example, a program and a screensaver, it can be important.) So, if a program is called "MyVBapp.exe", retreiving the value of <code>App.EXEName</code> would look like this:
Visual Basic provides the <code>App</code> object, which has a property called <code>EXEName</code> that contains the program's filename ''without the extension''. (For most uses, this doesn't matter, but for code shared between, for example, a program and a screensaver, it can be important.) So, if a program is called "MyVBapp.exe", retreiving the value of <code>App.EXEName</code> would look like this:
<lang vb>appname = App.EXEName 'appname = "MyVBapp"</lang>
<syntaxhighlight lang="vb">appname = App.EXEName 'appname = "MyVBapp"</syntaxhighlight>


Alternately, Visual Basic can make an [[API]] call:
Alternately, Visual Basic can make an [[API]] call:
<lang vb>Declare Function GetModuleFileName Lib "kernel32" Alias "GetModuleFileNameA" (ByVal hModule As Long, ByVal lpFileName As String, ByVal nSize As Long) As Long
<syntaxhighlight lang="vb">Declare Function GetModuleFileName Lib "kernel32" Alias "GetModuleFileNameA" (ByVal hModule As Long, ByVal lpFileName As String, ByVal nSize As Long) As Long
Dim fullpath As String * 260, appname As String, namelen As Long
Dim fullpath As String * 260, appname As String, namelen As Long
namelen = GetModuleFileName (0, fullpath, 260)
namelen = GetModuleFileName (0, fullpath, 260)
Line 1,979: Line 2,099:
Else
Else
appname = fullpath
appname = fullpath
End If</lang>
End If</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
Assuming we're running a script file named "program_name.wren":
Assuming we're running a script file named "Program_name.wren":
<lang ecmascript>import "os" for Process
<syntaxhighlight lang="wren">import "os" for Process


System.print("My name is %(Process.allArguments[1])")</lang>
System.print("My name is %(Process.allArguments[1])")</syntaxhighlight>


{{out}}
{{out}}
<pre>
<pre>
My name is program_name.wren
My name is Program_name.wren
</pre>
</pre>


Line 1,996: Line 2,116:
===Linux===
===Linux===
Makefile:
Makefile:
<lang make>FORMAT=-f elf
<syntaxhighlight lang="make">FORMAT=-f elf
RUN=./
RUN=./
BIN=scriptname
BIN=scriptname
Line 2,014: Line 2,134:
clean:
clean:
-rm $(BIN)
-rm $(BIN)
-rm $(OBJ)</lang>
-rm $(OBJ)</syntaxhighlight>


scriptname.asm:
scriptname.asm:
<lang asm>bits 32
<syntaxhighlight lang="asm">bits 32


section .data
section .data
Line 2,088: Line 2,208:
mov eax, sys_exit
mov eax, sys_exit
mov ebx, 0
mov ebx, 0
int kernel</lang>
int kernel</syntaxhighlight>


===FreeBSD/Mac OS X===
===FreeBSD/Mac OS X===
Makefile:
Makefile:
<lang make># FreeBSD defaults
<syntaxhighlight lang="make"># FreeBSD defaults


FORMAT=-f elf
FORMAT=-f elf
Line 2,118: Line 2,238:
clean:
clean:
-rm $(BIN)
-rm $(BIN)
-rm $(OBJ)</lang>
-rm $(OBJ)</syntaxhighlight>


scriptname.asm:
scriptname.asm:
<lang asm>bits 32
<syntaxhighlight lang="asm">bits 32


section .data
section .data
Line 2,199: Line 2,319:
mov eax, sys_exit
mov eax, sys_exit
sub esp, 4
sub esp, 4
int kernel</lang>
int kernel</syntaxhighlight>


===Windows===
===Windows===
Makefile:
Makefile:
<lang make>FORMAT=-f win32
<syntaxhighlight lang="make">FORMAT=-f win32
BIN=scriptname.exe
BIN=scriptname.exe
OBJ=scriptname.obj
OBJ=scriptname.obj
Line 2,221: Line 2,341:
clean:
clean:
-rm $(BIN)
-rm $(BIN)
-rm $(OBJ)</lang>
-rm $(OBJ)</syntaxhighlight>


scriptname.asm:
scriptname.asm:
<lang asm>bits 32
<syntaxhighlight lang="asm">bits 32


section .data
section .data
Line 2,317: Line 2,437:


push 0
push 0
call ExitProcess</lang>
call ExitProcess</syntaxhighlight>


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang Yabasic>print peek$("program_name")
<syntaxhighlight lang="yabasic">print peek$("program_name")


s$ = system$("cd")
s$ = system$("cd")
n = len(s$)
n = len(s$)
print left$(s$, n - 2), "\\", peek$("program_name")</lang>
print left$(s$, n - 2), "\\", peek$("program_name")</syntaxhighlight>


=={{header|Zig}}==
=={{header|Zig}}==
<lang zig>const std = @import("std");
<syntaxhighlight lang="zig">const std = @import("std");


const debug = std.debug;
const debug = std.debug;
Line 2,340: Line 2,460:


debug.warn("{}\n", .{program_name});
debug.warn("{}\n", .{program_name});
}</lang>
}</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
C's argv is exposed to the zkl runtime so if file bbb.zkl contains:
C's argv is exposed to the zkl runtime so if file bbb.zkl contains:
<lang zkl>#!/Homer/craigd/Bin/zkl
<syntaxhighlight lang="zkl">#!/Homer/craigd/Bin/zkl
println(System.argv);</lang>
println(System.argv);</syntaxhighlight>
Then (on Unix like OSes)
Then (on Unix like OSes)
<lang zkl>./bbb.zkl
<syntaxhighlight lang="zkl">./bbb.zkl
zkl bbb.zkl</lang>
zkl bbb.zkl</syntaxhighlight>
both print
both print
<pre>
<pre>
Line 2,354: Line 2,474:
</pre>
</pre>
On Unix, zkl is actually a shell script:
On Unix, zkl is actually a shell script:
<lang bash>#!/bin/sh
<syntaxhighlight lang="bash">#!/bin/sh
# A bash script to run zkl if you haven't jumped
# A bash script to run zkl if you haven't jumped
# through all the Unix hoops to put the bits in the "right" places
# through all the Unix hoops to put the bits in the "right" places
Line 2,368: Line 2,488:
export zklRoot
export zklRoot
#set -o noglob
#set -o noglob
LD_LIBRARY_PATH=$zklRoot/Lib $zklRoot/Bin/zkl "$@"</lang>
LD_LIBRARY_PATH=$zklRoot/Lib $zklRoot/Bin/zkl "$@"</syntaxhighlight>
On Windows, no launch script (windows knows where the DLLs are) but argv[0] can be messed up.
On Windows, no launch script (windows knows where the DLLs are) but argv[0] can be messed up.


{{omit from|EasyLang}}

{{omit from|GUISS}}
{{omit from|GUISS}}
{{omit from|Retro}}
{{omit from|Retro}}

Revision as of 10:30, 29 January 2024

Task
Program name
You are encouraged to solve this task according to the task description, using any language you may know.

The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)

Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV.

See also Command-line arguments

Examples from GitHub.

11l

:start:
print(‘Program: ’:argv[0])

68000 Assembly

Works with: NEOGEO

The name of the game is stored on the cartridge at memory address $000200. It is exactly 16 characters and is padded with spaces (ASCII 32). Since there is no null terminator after this string, use its size to terminate a printing loop.

LEA $000200,A3
JSR PrintString ;(my print routine is 255-terminated and there just so happens to be an FF after the name of the game.)
Output

[Ninja Adventure]

AArch64 Assembly

Without built-in CRT, argc and argv are stored in the stack. The format looks like:

sp+0  = argc
sp+8  = argv[0]
sp+16 = argv[1] ...

Each item of argv is a pointer to a null-terminated 8-bit string.

.equ STDOUT, 1
.equ SVC_WRITE, 64
.equ SVC_EXIT, 93

.text
.global _start

_start:
	stp x29, x30, [sp, -16]!
	mov x29, sp
	ldr x0, [sp, 24] // argv[0]
	bl _strlen // strlen(argv[0])
	mov x2, x0
	mov x0, #STDOUT
	ldr x1, [sp, 24]
	bl _write // write(stdout, argv[0], strlen(argv[0]))
	ldp x29, x30, [sp], 16
	mov x0, #0
	b _exit // exit(0);

// ssize_t _strlen(const char *str)
_strlen:
	mov x1, x0
	mov x0, #-1
1:	add x0, x0, #1
	ldrb w2, [x1, x0]
	cbnz x2, 1b
	ret

.text
//////////////// system call wrappers
// ssize_t _write(int fd, void *buf, size_t count)
_write:
	stp x29, x30, [sp, -16]!
	mov x8, #SVC_WRITE
	mov x29, sp
	svc #0
	ldp x29, x30, [sp], 16
	ret

// void _exit(int retval)
_exit:
	mov x8, #SVC_EXIT
	svc #0

Ada

Being a compiled language, Ada has difficulties accessing source code filenames. But it is easy to access the executable's filename, using the function Command_Name defined in Ada.Command_Line:

with Ada.Command_Line, Ada.Text_IO;

procedure Command_Name is
begin
   Ada.Text_IO.Put_Line(Ada.Command_Line.Command_Name);
end Command_Name;

Aime

The program command line arguments are accessible via the argc()/argv() functions. The program name is the first in the list of arguments.

o_text(argv(0));
o_byte('\n');

ALGOL 68

BEGIN
   print ((program idf, newline))
END
Output:
$ a68g Program_name.a68
Program_name.a68
$ 

Amazing Hopper

El primer parámetro en Hopper y sus sabores, siempre será el nombre del programa.

#include <hbasic.h>
Begin
   GetParam(name File)
   Print("My Program name: ", name File,Newl)
End
Output:
$ hopper myname.bas
My Program name: myname.bas
$ 

Applesoft BASIC

10 GOSUB 40"GET PROGRAM NAME
20 PRINT N$
30 END

40 REMGET PROGRAM NAME
50 GOSUB 100"GET INPUT BUFFER
60 GOSUB 200"REMOVE RUN PREFIX
70 GOSUB 300"REMOVE , SUFFIXES
80 GOSUB 400"TRIM SPACES
90 RETURN

100 REMGET INPUT BUFFER
110 N$ = ""
120 FOR I = 512 TO 767
130     B =  PEEK (I) - 128
140     IF B < 32 THEN  RETURN
150     N$ = N$ +  CHR$ (B)
160 NEXT I
170 RETURN

200 REMREMOVE RUN PREFIX
210 P = 1
220 FOR I = 1 TO 3
230     FOR J = P TO LEN(N$)
240         C$ =  MID$ (N$,J,1)
250         P = P + 1
260         IF C$ = " " THEN  NEXT J
270         IF C$ = MID$("RUN",I,1) THEN NEXT I:N$ =  MID$(N$,P,LEN(N$)-P+1):RETURN
280 PRINT "YOU NEED TO RUN THIS PROGRAM USING THE  RUN COMMAND FROM DOS."
290 END

300 REMREMOVE , SUFFIXES
310 L =  LEN (N$)
320 FOR I = 1 TO L
330     C$ =  MID$ (N$,I,1)
340     IF C$ = "," THEN N$ =  LEFT$(N$,I - 1): RETURN
350 NEXT I
360 RETURN

400 REMTRIM SPACES
410 GOSUB 600

500 REMLEFT TRIM SPACES
510 L = LEN(N$) - 1
520 FOR I = L TO 0 STEP -1
530     IF I < 0 THEN RETURN
540     IF LEFT$ (N$,1) <> " " THEN RETURN
550     IF I THEN N$ = RIGHT$ (N$, I)
560 NEXT I
570 N$ = "
580 RETURN

600 REMRIGHT TRIM SPACES
610 L = LEN(N$) - 1
620 FOR I = L TO 0 STEP -1
630     IF I < 0 THEN RETURN
640     IF RIGHT$ (N$,1) <> " " THEN RETURN
650     IF I THEN N$ = LEFT$ (N$, I)
660 NEXT I
670 N$ = "
680 RETURN

ARM Assembly

Works with: as version Raspberry Pi
/* ARM assembly Raspberry PI  */
/*  program namepgm.s   */
/* Constantes    */
.equ STDOUT, 1
.equ WRITE,  4
.equ EXIT,   1
/* Initialized data */
.data
szMessage: .asciz "Program : "       @ 
szRetourLigne: .asciz "\n"


.text
.global main 
main:	
    push {fp,lr}    /* save des  2 registres */
    add fp,sp,#8    /* fp <- adresse début */
    ldr r0, iAdrszMessage         @ adresse of message
    bl affichageMess            @ call function
    ldr r0,[fp,#4]                 @ recup name of program in command line
    bl affichageMess            @ call function
    ldr r0, iAdrszRetourLigne         @ adresse of message
    bl affichageMess            @ call function
 
 /* fin standard du programme */
    mov r0, #0                  @ return code
    pop {fp,lr}                 @restaur des  2 registres 
    mov r7, #EXIT              @ request to exit program
    swi 0                       @ perform the system call
iAdrszMessage: .int szMessage
iAdrszRetourLigne: .int szRetourLigne	
/******************************************************************/
/*     affichage des messages   avec calcul longueur              */ 
/******************************************************************/
/* r0 contient l adresse du message */
affichageMess:
	push {fp,lr}    /* save des  2 registres */ 
	push {r0,r1,r2,r7}    /* save des autres registres */
	mov r2,#0   /* compteur longueur */
1:	      /*calcul de la longueur */
        ldrb r1,[r0,r2]  /* recup octet position debut + indice */
	cmp r1,#0       /* si 0 c est fini */
	beq 1f
	add r2,r2,#1   /* sinon on ajoute 1 */
	b 1b
1:	/* donc ici r2 contient la longueur du message */
	mov r1,r0        /* adresse du message en r1 */
	mov r0,#STDOUT      /* code pour écrire sur la sortie standard Linux */
        mov r7, #WRITE                  /* code de l appel systeme "write" */
        swi #0                      /* appel systeme */
	pop {r0,r1,r2,r7}     /* restaur des autres registres */
	pop {fp,lr}    /* restaur des  2 registres */ 
        bx lr	        /* retour procedure */

AutoHotkey

MsgBox, % A_ScriptName

AWK

# syntax: TAWK -f PROGRAM_NAME.AWK
#
# GAWK can provide the invoking program name from ARGV[0] but is unable to
# provide the AWK script name that follows -f.  Thompson Automation's TAWK
# version 5.0c, last released in 1998 and no longer commercially available, can
# provide the AWK script name that follows -f from the PROGFN built-in
# variable.  It should also provide the invoking program name, E.G. TAWK, from
# ARGV[0] but due to a bug it holds the fully qualified -f name instead.
#
# This example is posted here with hopes the TAWK built-in variables PROGFN
# (PROGram File Name) and PROGLN (PROGram Line Number) be added to GAWK by its
# developers.
#
BEGIN {
    printf("%s -f %s\n",ARGV[0],PROGFN)
    printf("line number %d\n",PROGLN)
    exit(0)
}
Output:
TAWK -f PROGRAM_NAME.AWK
C:\program_name.awk -f program_name.awk
line number 16

GAWK -f PROGRAM_NAME.AWK
gawk -f
line number 0

BASIC

Many BASICs -- notably older DOS BASICs, and especially DOS MS BASICs -- do not provide any way to retrieve the program's name.

FreeBASIC

Unlike most MS BASICs, FreeBASIC provides a parsed version of COMMAND$ (called as COMMAND$(n)). COMMAND$(0) is the program's name:

appname = COMMAND$(0)

Additionally, FreeBASIC also provides an analog of C's argc/argv[], called __FB_ARGC__ and __FB_ARGV__. __FB_ARGV__ can be used to get the program's name like this:

appname = *__FB_ARGV__(0)

See also: PowerBASIC, PureBasic, Visual Basic.

BBC BASIC

      SYS "GetCommandLine" TO cl%
      PRINT $$cl%

IS-BASIC

100 PROGRAM "Name1.bas"(A,B,C,S$)
110 CHAIN "Name2.BAS"(A,B,C,S$)

edit 1
100 PROGRAM "Name2.bas"(A,B,C,S$)
110 PRINT A,B,C,S$

edit 0
start(1,2,3,"Hello")

BaCon

To get the name with which the program was invoked:

PRINT TOKEN$(ARGUMENT$, 1)

To get the full path:

PRINT ME$

uBasic/4tH

CMD(1) returns a string with the filename - SHOW() prints this string.

Print Show(Cmd(1))

Blue

Linux/x86-64. Will print the name of the executable from "argv[0]" as provided.

global _start

: syscall ( num:eax -- result:eax ) syscall ;

: exit ( status:edi -- noret ) 60 syscall ;
: bye ( -- noret ) 0 exit ;

: write ( buf:esi len:edx fd:edi -- ) 1 syscall drop ;

1 const stdout

: print ( buf len -- ) stdout write ;

: newline ( -- ) s" \n" print ;
: println ( buf len -- ) print newline ; 

: find0 ( start:rsi -- end:rsi ) lodsb 0 cmp latest xne ; 
: cstrlen ( str:rdi -- len:rsi ) dup find0 swap sub dec ;
: cstr>str ( cstr:rdx -- str:rsi len:rdx ) dup cstrlen xchg ;

: print-arg ( arg -- ) cstr>str println ;

: arg0 ( rsp -- rsp ) 8 add @ ; inline

: _start ( rsp -- noret ) arg0 print-arg bye ;

BQN

•name

C

It might not be very useful for a C program to access source filenames, because C code must be compiled into an executable, and anything could have happened to the source file after the compilation. However, C can access the executable's name in argv[0].

  • argv[0] might be the name of an executable in the PATH, or it might be an absolute or relative path to the executable. At least with Unix, the parent process can set argv[0] to any string, so argv[0] might not be the real name. It is best to pretend that argv[0] has the correct value, but mind that argv[0] might not be an actual file.
#include <stdio.h>

int main(int argc, char **argv) {
	printf("Executable: %s\n", argv[0]);

	return 0;
}

To get the source information about some part of code, use compiler defined macros. Most compilers support them or some variation of.

#include <stdio.h>
 
int main()
{
	printf("This code was in file %s in function %s, at line %d\n",\
		__FILE__, __FUNCTION__, __LINE__);
	return 0;
}

BSD

BSD provides two more ways to get the program's name.

  1. __progname is the filename from argv[0] (so if argv[0] is a path, then __progname is only the filename). No header file declares __progname, so programs must declare extern char __progname; to use it.
  2. ucomm always gives the real filename of the executable, even if argv[0] has a different name. ucomm is a field in the process information; ps -O ucomm prints it. Other than ps(1) and top(1), few programs access ucomm. There is a C interface to the process information, but it often changes between BSD versions.

Starting with OpenBSD 5.0, ucomm is field p_comm of struct kinfo_proc, and kvm_getprocs() in libkvm can fill this struct. (Rosetta Code will welcome contributions for other BSD variants.)

Library: BSD libc
Works with: OpenBSD version 5.0

To compile myname.c: make myname LDLIBS=-lkvm

/* myname.c */

#include <sys/param.h>
#include <sys/sysctl.h>	/* struct kinfo_proc */
#include <err.h>
#include <fcntl.h>	/* O_RDONLY */
#include <kvm.h>
#include <limits.h>	/* _POSIX2_LINE_MAX */
#include <stdio.h>

int
main(int argc, char **argv) {
	extern char *__progname;	/* from crt0.o */

	struct kinfo_proc *procs;
	kvm_t *kd;
	int cnt;
	char errbuf[_POSIX2_LINE_MAX];

	printf("argv[0]: %s\n", argv[0]);
	printf("__progname: %s\n", __progname);

	kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, errbuf);
	if (kd == NULL)
		errx(1, "%s", errbuf);
	procs = kvm_getprocs(kd, KERN_PROC_PID, getpid(),
	    sizeof procs[0], &cnt);
	if (procs == NULL)
		errx(1, "%s", kvm_geterr(kd));
	if (cnt != 1)
		errx(1, "impossible");

	printf("p_comm: %s\n", procs[0].p_comm);

	kvm_close(kd);
	return 0;
}

The program can have three different names!

$ perl -e 'exec {"./myname"} "/nobin/fakename"' 
argv[0]: /nobin/fakename
__progname: fakename
ucomm: myname

Windows

GetModuleFileName, from the Win32 API, provides the correct path to the current executable file.

Library: Win32
#include <windows.h>
#include <stdlib.h>
#include <wchar.h>

/*
 * Returns the path to the current executable file, in a newly
 * allocated buffer. Use free() to free it.
 */
wchar_t *
exepath(void)
{
	wchar_t *buf, *newbuf;
	long blen, flen;

	/*
	 * Most paths fit in MAX_PATH == 260 characters, but very
	 * long UNC paths might require a larger buffer.
	 */
	buf = NULL;
	for (blen = MAX_PATH; 1; blen += MAX_PATH) {
		/* Enlarge buffer. */
		newbuf = realloc(buf, blen * sizeof buf[0]);
		if (newbuf == NULL) {
			free(buf);
			return NULL;
		}
		buf = newbuf;

		flen = GetModuleFileNameW(NULL, buf, blen);
		if (flen == 0) {
			free(buf);
			return NULL;
		}
		if (flen < blen)
			return buf;
	}
}

/*
 * Print the path to this executable.
 */
int
main()
{
	wchar_t *path;

	path = exepath();
	if (path == NULL) {
		wprintf(L"Sorry, an error occured.\n");
		return 1;
	}

	wprintf(L"Path to executable: %ls\n", path);

	free(path);
	return 0;
}
Path to executable: C:\Users\kernigh\Documents\field\scratch.exe

C#

This effectively outputs the executable name, file path, and any arguments for the current program.

using System;
namespace ProgramName
{
	class Program
	{
		static void Main(string[] args)
		{
			Console.Write(Environment.CommandLine);
		}
	}
}

In a C# application with a reference to System.Windows.Forms, the following can be used to retrieve the executable name and arguments without the full path.

using System;
namespace ProgramName
{
	class Program
	{
		static void Main(string[] args)
		{
			// Extracts the filename from the full path
			System.IO.FileInfo exeInfo = new System.IO.FileInfo(System.Windows.Forms.Application.ExecutablePath);
			Console.Write(exeInfo.Name);
			
			// Writes all arguments to the console
			foreach (string argument in args)
			{
				Console.Write(" " + argument);
			}
		}
	}
}

C++

C++ can access the executable's filename through the arguments to main().

#include <iostream>

using namespace std;

int main(int argc, char **argv) {
	char *program = argv[0];
	cout << "Program: " << program << endl;
}

Clojure

":";exec lein exec $0 ${1+"$@"}
":";exit

(ns scriptname
  (:gen-class))

(defn -main [& args]
  (let [program (first *command-line-args*)]
    (println "Program:" program)))

(when (.contains (first *command-line-args*) *source-path*)
  (apply -main (rest *command-line-args*)))

COBOL

Works with: GnuCOBOL

COBOL has an internal PROGRAM-ID name, and then the external invocation name.

       identification division.
       program-id. sample.

       data division.
       working-storage section.
       01 progname pic x(16).

       procedure division.
       sample-main.

       display 0 upon argument-number
       accept progname from argument-value
       display "argument-value zero :" progname ":"

       display "function module-id  :" function module-id ":"

       goback.
       end program sample.
Output:
prompt$ cobc -xj progname.cob 
argument-value zero :./progname      :
function module-id  :sample:

CoffeeScript

scriptname.coffee:

#!/usr/bin/env coffee

main = () ->
  program = __filename
  console.log "Program: " + program

if not module.parent then main()

Common Lisp

Shebangs require a special tweak to ~/.clisprc.lisp.

;;; Play nice with shebangs
(set-dispatch-macro-character #\# #\!
 (lambda (stream character n)
  (declare (ignore character n))
  (read-line stream nil nil t)
  nil))
#!/bin/sh
#|
exec clisp -q -q $0 $0 ${1+"$@"}
exit
|#

;;; Usage: ./scriptname.lisp

(defun main (args)
 (let ((program (car args)))
  (format t "Program: ~a~%" program)
  (quit)))

;;; With help from Francois-Rene Rideau
;;; http://tinyurl.com/cli-args
(let ((args
       #+clisp (ext:argv)
       #+sbcl sb-ext:*posix-argv*
       #+clozure (ccl::command-line-arguments)
       #+gcl si:*command-args*
       #+ecl (loop for i from 0 below (si:argc) collect (si:argv i))
       #+cmu extensions:*command-line-strings*
       #+allegro (sys:command-line-arguments)
       #+lispworks sys:*line-arguments-list*
     ))

  (if (member (pathname-name *load-truename*)
              args
              :test #'(lambda (x y) (search x y :test #'equalp)))
    (main args)))

D

#!/usr/bin/env rdmd

import std.stdio;

void main(in string[] args) {
    writeln("Program: ", args[0]);
}
Output:
C:\rosetta>program_name.exe
Program: program_name.exe
$ dmd scriptname.d
$ ./scriptname
Program: ./scriptname

If the system is configured, the D programming language offers an 'interpreted-looking' mode, which exhibits slightly different behavior than the normal compilation:

$ ./scriptname.d
Program: /tmp/.rdmd/Users/andrew/Desktop/src/scriptname/scriptname.d.D3B32385A31B968A3CF8CAF1E1426E5F


Alternative method using built-in function thisExePath()

Works with: D version 2.064+
// thisExePath function was introduced in D 2.064 (November 5, 2013)

import std.file;
import std.stdio;

void main(string[] args)
{
    writeln("Program: ", thisExePath());
}
Output:
Z:\rosettacode>program_name.exe
Program: Z:\rosettacode\program_name.exe

Dart

#!/usr/bin/env dart

main() {
	var program = new Options().script;
	print("Program: ${program}");
}

Delphi

program ProgramName;

{$APPTYPE CONSOLE}

begin
  Writeln('Program name: ' + ParamStr(0));
  Writeln('Command line: ' + CmdLine);
end.

Déjà Vu

!print( "Name of this file: " get-from !args 0 )

EchoLisp

(js-eval "window.location.href")
     "http://www.echolalie.org/echolisp/"

Elena

ELENA 4.x :

import extensions;
 
public program()
{
    console.printLine(program_arguments.asEnumerable());  // the whole command line
 
    console.printLine(program_arguments[0]); // the program name
}

Emacs Lisp

:;exec emacs -batch -l $0 -f main $*

;;; Shebang from John Swaby
;;; http://www.emacswiki.org/emacs/EmacsScripts

(defun main ()
  (let ((program (nth 2 command-line-args)))
    (message "Program: %s" program)))

load-file-name is the ".el" or ".elc" currently being loaded. Within a batch -l it will be the script name, but within sub-loads like require etc it is that sub-load.

EMal

writeLine("path: " + Runtime.path)
writeLine("name: " + Runtime.name)
writeLine("args: " + Runtime.args)
Output:
emal.exe Org\RosettaCode\ProgramName.emal sample arguments
path: C:\tmp\Org\RosettaCode\ProgramName.emal
name: ProgramName.emal
args: [sample,arguments]

Erlang

If Erlang is used as a script language the function escript:script_name/0 will return the program name. When compiled Erlang's macros hold information about the running module.

%% Compile
%%
%% erlc scriptname.erl
%%
%% Run
%%
%% erl -noshell -s scriptname

-module(scriptname).
-export([start/0]).

start() ->
  Program = ?FILE,
  io:format("Program: ~s~n", [Program]),
  init:stop().

Euphoria

constant cmd = command_line()
puts(1,cmd[2])

F#

This code correctly prints the program name in three modes:

  • Run as a compiled program (either scriptname.exe in Windows, or mono scriptname.exe in Unix)
  • Run as an interpreted program (fsharpi scriptname.fsx)
  • Run as a dotslashed program in Unix (./scriptname.fsx)
#light (*
	exec fsharpi --exec $0 --quiet
*)

let scriptname =
    let args = System.Environment.GetCommandLineArgs()

    let arg0 = args.[0]

    if arg0.Contains("fsi") then
        let arg1 = args.[1]
        if arg1 = "--exec" then
            args.[2]
        else
            arg1
    else
        arg0

let main =
    printfn "%s" scriptname

Factor

#! /usr/bin/env factor
 
USING: namespaces io command-line ;
IN: scriptname
 
: main ( -- ) script get print ;
 
MAIN: main

Forth

Works with: GNU Forth
0 arg type cr    \ gforth or gforth-fast, for example
1 arg type cr     \ name of script

Fortran

Please find example runs in the comments at the beginning of the FORTRAN2003 source. Program name verification can deter system attackers. Therefore, the code is provided as a separate easily reused module.

! program run with invalid name path/f
!
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Sun Jun  2 00:18:31
!
!a=./f && make $a && OMP_NUM_THREADS=2 $a < unixdict.txt
!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f
!
!Compilation finished at Sun Jun  2 00:18:31



! program run with valid name path/rcname
! 
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Sun Jun  2 00:19:01
!
!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o rcname && ./rcname
! ./rcname approved.
! program continues...
!
!Compilation finished at Sun Jun  2 00:19:02


module sundry

contains

  subroutine verify_name(required)
    ! name verification reduces the ways an attacker can rename rm as cp.
    character(len=*), intent(in) :: required
    character(len=1024) :: name
    integer :: length, status
    ! I believe get_command_argument is part of the 2003 FORTRAN standard intrinsics.
    call get_command_argument(0, name, length, status)
    if (0 /= status) stop
    if ((len_trim(name)+1) .ne. (index(name, required, back=.true.) + len(required))) stop
    write(6,*) trim(name)//' approved.'
  end subroutine verify_name

end module sundry

program name
  use sundry
  call verify_name('rcname')
  write(6,*)'program continues...'
end program name

FreeBASIC

' FB 1.05.0 Win64

Print "The program was invoked like this => "; Command(0) + " " + Command(-1)
Print "Press any key to quit"
Sleep


FutureBasic

There are several ways to retrieve the program name. These functions return a string containing the name that can be used in various ways.

print fn ProcessInfoProcessName
print fn RunningApplicationLocalizedName( fn RunningApplicationCurrentApplication )

Gambas

Click this link to run this code

Public Sub Main()
Dim sTemp As String

Print "Command to start the program was ";;

For Each sTemp In Args.All
  Print sTemp;;
Next

End

Output:

Command to start the program was  ./CLIOnly.gambas Hello World!

Genie

[indent=4]
init
    print args[0]
    print Path.get_basename(args[0])
    print Environment.get_application_name()
    print Environment.get_prgname()
Output:
prompt$ valac programname.gs
prompt$ ./programname
./programname
programname
(null)
(null)

Go

scriptname.go:

package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Println("Program:", os.Args[0])
}
Command line session:
> go build scriptname.go
> ./scriptname
Program: ./scriptname
> mv scriptname newname
> ./newname
Program: ./newname

Groovy

All the Java solutions work equally well under Groovy when the program is invoked through the "main" method of a class. However, if a Groovy program is invoked as a script, the script runs as an instance method of itself as the instantiating class. If the script is running as a compiled string, the Groovy environment under which it is running assigns it a name.

If you want the script filename, use:

#!/usr/bin/env groovy

def program = getClass().protectionDomain.codeSource.location.path

println "Program: " + program

But if you just want the class name, there are easier ways.

So, just typing in and running the following in the GroovyConsole environment:

println this.class.getName()

yields the following on the first run:

ConsoleScript0

and the following on the third run:

ConsoleScript2

But if we save this one line script under the filename "Autonomous.groovy" and then load the file into the console, we get this on every run:

Autonomous

Using the package statement and an appropriate directory hierarchy to provide namespace semantics works exactly as it does in Java.

Haskell

Haskell has an impure function for this.

import System (getProgName)

main :: IO ()
main = getProgName >>= putStrLn . ("Program: " ++)

Icon and Unicon

procedure main()
write(&progname)    # obtain and write out the program name from the keyword &progname
end

Io

#!/usr/bin/env io

main := method(
	program := System args at(0)

	("Program: " .. program) println
)

if (System args size > 0 and System args at(0) containsSeq("scriptname"), main)

J

#!/usr/bin/env jconsole

program =: monad : 0
	if. (#ARGV) > 1 do.
		> 1 { ARGV
	else.
		'Interpreted'
	end.
)

echo 'Program: ', program 0

exit ''

Jakt

The name of the program is stored in the first index of the array passed to main. This is the name of the compiled executable, so when using jakt -cr the value will be a path starting with build/.

fn main(arguments: [String]) {
    let program_name = arguments[0]
    println("{}", program_name)
}

Java

On one hand, this task is trivial for Java. Java code is (usually) compiled into bytecode as class files. There is exactly one class file per class, named <class name>.class (regardless of what the original source files were called or how classes were organized in the source). One executes Java code by executing some class which contains a main method, by running the command java <class name> <possible arguments>. Hence, it is guaranteed that the "name" of the executable is the class name (possibly prepended by package names, using the usual Java dot notation); and this is known in the main method at the time the code is written because it is the very class that the main method is in. Hence, the complicated solutions listed in this section do not gain anything that is not already known by the programmer at the time the code is written.

However, it is tedious to hard-code the class names if you need to do this in a lot of Java programs. Thus, a more interesting task is to write a snippet of Java code which, without modification, can be copy-and-pasted into the main method of any class and retrieve the class name. This is not trivial because in Java there is no way to use this in a static method to get the class it's in. Listed below are several notable, commonly-cited solutions for this.

You can get the listing of the arguments to the java command through a system property. The first one is the name of the main class that was run. This depends on a system property named "sun.java.command", which might not exist on all Java virtual machines.

public class ScriptName {
	public static void main(String[] args) {
		String program = System.getProperty("sun.java.command").split(" ")[0];
		System.out.println("Program: " + program);
	}
}

An alternate solution is to create a dummy inner class, and then retrieve its enclosing class (which is the class the main method is in) through reflection (though this will not work if the code is placed in a method in another source file--it will give the name of the class it is in inside that source file):

public class ScriptName {
	public static void main(String[] args) {
		Class c = new Object(){}.getClass().getEnclosingClass();
		System.out.println("Program: " + c.getName());
	}
}

A solution using the security manager:

public class ScriptName {
	public static void main(String[] args) {
		Class c = System.getSecurityManager().getClassContext()[0];
		System.out.println("Program: " + c.getName());
	}
}

A solution using the stack trace (requires Java 1.5+):

public class ScriptName {
	public static void main(String[] args) {
		String program = Thread.currentThread().getStackTrace()[1].getClassName();
		System.out.println("Program: " + program);
	}
}

JavaScript

This example is incorrect. Please fix the code and remove this message.

Details: Program name, not function name. Show sample output.

Suggestion: document.location.href is probably closer to task requirements (and better than a script name), plus arguments.callee.name is long dead. --Pete Lomax (talk) 23:29, 24 March 2022 (UTC)
There is no capability within the ECMA-262 standard (the standard for ECMAScript, the language underlying JavaScript) for a function to determine its name. Since objects in JavaScript are first class objects, variables and properties are only references to objects. The name of an object might be said to be the name used to reference it, however a single object may have many variables and properties that reference it, or none.

In some implementations, the following (non–standard) code will work:

function foo() {
  return arguments.callee.name;
}

But it will fail in in others. JavaScript also has anonymous functions that don't have a name, e.g.:

(function(){alert(arguments.callee.name);}())

returns an empty string or undefined even where the first example works.

Works with: Node.js

Node.js has a global variable for this.

#!/usr/bin/env node
/*jslint nodejs:true */

function main() {
	var program = __filename;
	console.log("Program: " + program);
}

if (!module.parent) { main(); }

Joy

#!/usr/bin/joy

argv first putchars.

Jsish

#!/usr/bin/env jsish
/* Program name, in Jsish */
puts('Executable:', Info.executable());
puts('Argv0     :', Info.argv0());
Output:
prompt$ jsish programName.jsi
Executable: /usr/local/bin/jsish
Argv0     : /home/btiffin/forge/jsi/jsi-test/rosetta/programName.jsi

Julia

Julia strips the program file name from ARGS, so this information is not available to the program from its command line arguments. Instead it is accessible via Base.source_path().

prog = basename(Base.source_path())
println("This program file is \"", prog, "\".")
Output:
This program file is "program_name.jl".

Kotlin

// version 1.0.6

// 'progname.kt' packaged as 'progname.jar'

fun main(args: Array<String>) {
    println(System.getProperty("sun.java.command"))  // may not exist on all JVMs
    println(System.getProperty("java.vm.name")) 
}
Output:
progname.jar
Java HotSpot(TM) 64-Bit Server VM

langur

The script name is in the _script variable (separate from the arguments, in the _args variable).

writeln "script: ", _script
writeln "script args: ", _args
Output:
script: ./testargs.langur
script args: []

Lasso

#!/usr/bin/lasso9

stdoutnl("Program: " + $argv->first)

Output:

$ lasso9 script_name.lasso 
Program: script_name.lasso

Liberty BASIC

nSize = _MAX_PATH + 2
lpFilename$ = space$(nSize); chr$(0)

    calldll #kernel32, "GetModuleFileNameA", _
        hModule     as ulong, _
        lpFilename$ as ptr, _
        nSize       as ulong, _
        result      as ulong
lpFilename$ = left$(lpFilename$,result)

print "Path to LB exe"
print lpFilename$
print "current program file (:last one on LRU list)"
print getLastLRU$(lbPath$)
end

Function getLastLRU$(lbPath$)
    open lbPath$+"lbasic404.ini" for input as #1
        while not(eof(#1))
            line input #1, a$
            if instr(a$, "recent files")<>0 then [readRecentFiles]
        wend
        getLastLRU$ = "* Failed: Recent files section not found *"
        close #1
        exit function

[readRecentFiles]
        nRecent = val(word$(a$,1))
        'print "nRecentFiles", nRecent
        for i = 1 to nRecent
            if eof(#1) then
                getLastLRU$ = "* Failed: File ended while in recent files section *"
                close #1
                exit function
            end if
            line input #1, a$
            'print i, a$
        next
    close #1
    getLastLRU$ = a$
end function

Output:

Path to LB exe
C:\progs\Liberty BASIC v4.04\liberty.exe
current program file (:last one on LRU list)
C:\progs\Liberty BASIC v4.04\untitled.bas

Lingo

put _player.applicationName
-- "lsw.exe"
put _movie.name
-- "lsw_win_d11.dir"

LLVM

Like C, LLVM can use argv to access the executable's filename.

$ make
llvm-as scriptname.ll
llc -disable-cfi scriptname.bc
gcc -o scriptname scriptname.s
./scriptname
Program: ./scriptname

Makefile


all: scriptname.ll
	llvm-as scriptname.ll
	llc scriptname.bc
	gcc -o scriptname scriptname.s
	./scriptname

clean:
	-rm scriptname
	-rm scriptname.s
	-rm scriptname.bc
@msg_main = internal constant [13 x i8] c"Program: %s\0A\00"

declare i32 @printf(i8* noalias nocapture, ...)

define i32 @main(i32 %argc, i8** %argv) {
	%program = load i8** %argv
	call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([13 x i8]* @msg_main, i32 0, i32 0), i8* %program)

	ret i32 0
}

Lua

Lua's arg is like C's argv.

#!/usr/bin/env lua

function main(arg)
	local program = arg[0]
	print("Program: " .. program)
end

if type(package.loaded[(...)]) ~= "userdata" then
	main(arg)
else
	module(..., package.seeall)
end

M2000 Interpreter

Module Checkit {
      Declare GetModuleFileName Lib "kernel32.GetModuleFileNameW"  {Long hModule, &lpFileName$, Long nSize}
      a$=string$(chr$(0), 260)
      namelen=GetModuleFileName(0, &a$, 260)
      a$=left$(a$, namelen)
      \\ normally m2000.exe is the caller of m2000.dll, the activeX script language
      Print Mid$(a$, Rinstr(a$, "\")+1)="m2000.exe" 
}
Checkit
\\ command$ return the file's path plus name of script
\\ we can use edit "callme.gsb" to paste these, and use USE callme to call it from M2000 console.
Module SayIt {
      Show
      Print command$
      a$=key$
}
SayIt

Make

NAME=$(CURDIR)/$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))

all:
	@echo $(NAME)

Mathematica/Wolfram Language

#!/usr/bin/env MathKernel -script
ScriptName[] = Piecewise[
	{
		{"Interpreted", Position[$CommandLine, "-script", 1] == {}}
	},
	$CommandLine[[Position[$CommandLine, "-script", 1][[1,1]] + 1]]
]
Program = ScriptName[];
Print["Program: " <> Program]

Mercury

:- module program_name.
:- interface.

:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.

main(!IO) :-
    % The first argument is used as the program name if it is not otherwise
    % available.  (We could also have used the predicate io.progname_base/4
    % if we did not want path preceding the program name.)
    io.progname("", ProgName, !IO),
    io.print_line(ProgName, !IO).

:- end_module program_name.

Mozart/Oz

Makefile:

all: test

test: scriptname
	./scriptname

scriptname: scriptname.oz
	ozc -x scriptname.oz

clean:
	-rm scriptname
	-rm *.exe

scriptname.oz:

functor
import
  System
  Application
  Property
define
  local ScriptName = {Property.get 'application.url'} in
    {System.printInfo "Script name: "#ScriptName#"\n"}
    {Application.exit 0}
  end
end

Nanoquery

println args[1]
Output:
programname.nq

Nemerle

using System.Environment;
...
def program_name = GetCommandLineArgs()[0];
...

NetRexx

/* NetRexx */
options replace format comments java crossref symbols nobinary

package org.rosettacode.samples

say 'Source: ' source
say 'Program:' System.getProperty('sun.java.command')
return

Output

Called directly:

$ java org.rosettacode.samples.RProgramName
Source:  Java method RProgramName.nrx
Program: org.rosettacode.samples.RProgramName

When bundled inside a JAR file and referenced as the application entry point via the manifest's Main-Class header:

$ java -jar pn.jar 
Source:  Java method RProgramName.nrx
Program: pn.jar

newLISP

newLISP has a function, (main-args int) for this.

#!/usr/bin/env newlisp

(let ((program (main-args 1)))
  (println (format "Program: %s" program))
  (exit))

Nim

import os
echo getAppFilename() # Prints the full path of the executed file
echo paramStr(0) # Prints argv[0]

Oberon-2

Works with oo2c Version 2

MODULE ProgramName;
IMPORT 
  NPCT:Args,
  Out;
BEGIN
  Out.Object("Program name: " + Args.Get(0));Out.Ln
END ProgramName.

Output:

Program name: ./ProgramName

Objective-C

scriptname.m:

#import <Foundation/Foundation.h>

int main(int argc, char **argv) {
	@autoreleasepool {

		char *program = argv[0];
		printf("Program: %s\n", program);

		// Alternatively:
		NSString *program2 = [[NSProcessInfo processInfo] processName];
		NSLog(@"Program: %@\n", program2);

	}

	return 0;
}
$ gcc -o scriptname -framework foundation scriptname.m
$ ./scriptname 
Program: ./scriptname

OCaml

let () =
  print_endline Sys.executable_name;
  print_endline Sys.argv.(0)
$ ocamlc -o prog_name.bye prog_name.ml
$ ocamlopt -o prog_name.opt prog_name.ml

$ ocaml prog_name.ml
/usr/bin/ocaml
prog_name.ml

$ ./prog_name.bye
./prog_name.bye
./prog_name.bye

$ ./prog_name.opt
/tmp/prog_name.opt
./prog_name.opt

Octave

function main()
	program = program_name();
	printf("Program: %s", program);
endfunction

main();

Ol

First argument of *vm-args* is an executing program name.

(print (car *vm-args*))

Order

This is relatively trivial in Order, as the program being executed is a macro expression in the current C program file being read by the compiler:

__FILE__

When including another file containing another ORDER_PP expression, within that file the __FILE__ macro will expand to the name of that file; but arguably that expression constitutes a separate Order program within the greater C project.

PARI/GP

GP does not have access to the name of the program running (especially since it is usually run from the REPL gp). PARI has the same access to argv[0] as C.

Pascal

program ScriptName;
var
	prog : String;
begin
	prog := ParamStr(0);
	write('Program: ');
	writeln(prog)
end.

Perl

#!/usr/bin/env perl

use strict;
use warnings;

sub main {
	my $program = $0;
	print "Program: $program\n";
}

unless(caller) { main; }

$0 includes the full path if a script is run as say perl /some/dir/foo.pl. The FindBin module can give just the basename. This can be good for printing in diagnostics etc.

use FindBin;
print "Program name $FindBin::Script\n";

Phix

with javascript_semantics
string cl2 = command_line()[2]
printf(1,"%s\n",cl2)                -- full path
printf(1,"%s\n",get_file_name(cl2)) -- eg test.exw or test.exe or test.htm
printf(1,"%s\n",get_file_base(cl2)) -- eg test

Phixmonti

argument 1 get ?

PHP

PHP has a global dictionary for this.

<?php
$program = $_SERVER["SCRIPT_NAME"];
echo "Program: $program\n";
?>

PicoLisp

The function 'cmd' returns the command name.

: (cmd)
-> "/usr/bin/picolisp"

PowerBASIC

Previous versions of PowerBASIC (PB/Win 8 or older; PB/CC 4 or older) have to make an API call:

#INCLUDE "Win32API.inc"
'[...]
DIM fullpath AS ASCIIZ * 260, appname AS STRING
GetModuleFileNameA 0, fullpath, 260
IF INSTR(fullpath, "\") THEN
    appname = MID$(fullpath, INSTR(-1, fullpath, "\") + 1)
ELSE
    appname = fullpath
END IF
Works with: PowerBASIC for Windows version 9
Works with: PowerBASIC Console Compiler version 5

Recent versions of PowerBASIC provide the EXE object; EXE.NAME$ returns the program's name, while EXE.NAMEX$ returns the program's name and extension. (EXE.EXTN$ returns the extension only.) So, to get the program's name, we do this:

appname = EXE.NAMEX$

PowerShell

# write this in file <program.ps1>
$MyInvocation.MyCommand.Name 
# launch with <.\program>

Output:

program.ps1

Prolog

% SWI-Prolog version 8.0.0 for i686-linux.
% This will find itself, and return the knowledge base it is in.
file_name(F) :- true
   , M = user            % M is the module    .
   , P = file_name(_)    % P is the predicate .
   , source_file(M:P, F) % F is the file      .
   , \+ predicate_property(M:P, imported_from(_))
   .

Alternatively, you may prefer a list of all your knowledge bases; adding the following code to each of your knowledge bases will allow you to query findall(F, source_file(this_is_one_of_my_files, F), L)..

:- multifile(this_is_one_of_my_files). this_is_one_of_my_files.

PureBasic

PureBasic provides a way to retrieve the filename of the program being executed. It includes the file's path.

If OpenConsole()
  PrintN(ProgramFilename())
  
  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
  CloseConsole()
EndIf

Sample output when executing the above program compiled to an executible file called 'program name.exe':

H:\Data\Rosetta Code\program name.exe

Python

Python has at least two ways to get the script name: the traditional ARGV and the inspect module.

#!/usr/bin/env python

import sys

def main():
    program = sys.argv[0]
    print("Program: %s" % program)

if __name__ == "__main__":
    main()


#!/usr/bin/env python

import inspect

def main():
    program = inspect.getfile(inspect.currentframe())
    print("Program: %s" % program)

if __name__ == "__main__":
    main()

R

R's syntax is complicated, but doable.

#!/usr/bin/env Rscript

getProgram <- function(args) {
	sub("--file=", "", args[grep("--file=", args)])
}

args <- commandArgs(trailingOnly = FALSE)
program <- getProgram(args)

cat("Program: ", program, "\n")

q("no")

Racket

#!/usr/bin/env racket
#lang racket

(define (program) (find-system-path 'run-file))

(module+ main (printf "Program: ~a\n" (program)))

Raku

(formerly Perl 6)

Works with: rakudo version 2015-10-16

In Raku, the name of the program being executed is in the special global variable $*PROGRAM-NAME.

say $*PROGRAM-NAME;

Raven

ARGS list " " join "%s\n" print
Output:
raven arg_file.rv

REXX

The Rexx PARSE SOURCE instruction parses data describing the source of the program running. The language processor returns a string that does not change while the program is running. The source string contains operating system name, followed by either COMMAND, FUNCTION, or SUBROUTINE, depending on whether the program was called as a host command or from a function call in an expression or using the CALL instruction. These two tokens are followed by the complete path specification of the program file.

It should be noted that the format of the complete path varies depending upon the operating system.

/* Rexx */

Parse source . . pgmPath
Say pgmPath
Output
$ rexx RProgramName.rex
/tmp/RProgramName.rex

REXX does not support the use of arg(0) to access the program name. A workaround is to use a shell wrapper script to obtain and provide the invocation name of the wrapper:

#!/bin/sh
rexxbit.rexx $0 $*

Here is a rexx script that makes use of this:

say "The program is called " arg(1)

On TSO, this program

/*REXX program RANG1 in PDS N561985.PRIV.CLIST W. Pachl */             
Parse Source a b c   
Say 'a='a            
Say 'b='!!b          
Say 'c='c

yields

a=TSO                                              
b=COMMAND                                          
c=RANG1 SYS00056 N561985.PRIV.CLIST ? TSO ISPF ?   

version with various types of invokes

Used under Windows/XP and Windows 7 with the following REXXes:

  • Brexx
  • R4 REXX
  • REGINA REXX
  • Personal REXX
  • ROO REXX
  • ooRexx
/*REXX pgm displays the name (& possible path) of the REXX program name.*/
parse version _version
parse source _system _howInvoked _path

say right(_version '◄──►' space(arg(1) arg(2)), 79, '─')   /*show title.*/
say "     REXX's name of system being used:"  _system
say '     how the REXX program was invoked:'  _howInvoked
say '    name of the REXX program and path:'  _path

if arg()>1  then return 0              /*don't let this program recurse.*/
                                       /*Mama said that cursing is a sin*/
                                       /*invoke ourself with a  2nd arg.*/
call prog_nam  , 'subroutine'          /*call ourself as a  subroutine. */
zz = prog_nam( , 'function')           /*  "     "     " "  function.   */
                                       /*stick a fork in it, we're done.*/

output   when using BREXX with the input of:   command

───────────────────────────────────────────brexx 2.1.0 Mar 11 2003 ◄──► command
     REXX's name of system being used: MSDOS
     how the REXX program was invoked: COMMAND
    name of the REXX program and path: prog_nam.rex J:\-\BREXX\REXX16.EXE D:\WIN
DOWS\SYSTEM32\COMMAND.COM
────────────────────────────────────────brexx 2.1.0 Mar 11 2003 ◄──► subroutine
     REXX's name of system being used: MSDOS
     how the REXX program was invoked: PROCEDURE
    name of the REXX program and path: prog_nam.rex J:\-\BREXX\REXX16.EXE D:\WIN
DOWS\SYSTEM32\COMMAND.COM
──────────────────────────────────────────brexx 2.1.0 Mar 11 2003 ◄──► function
     REXX's name of system being used: MSDOS
     how the REXX program was invoked: FUNCTION
    name of the REXX program and path: prog_nam.rex J:\-\BREXX\REXX16.EXE D:\WIN
DOWS\SYSTEM32\COMMAND.COM

Output note (above):   note that the wrap-around of the output is an artifact of the BREXX interpreter, not the pasting of this output.

output   when using R4 REXX with the input of:   command

─────────────────────────────────────────────────REXX-r4 4.00 16 Aug 2015 ◄──► command
     REXX's name of system being used: Win32
     how the REXX program was invoked: COMMAND
    name of the REXX program and path: C:\PROG_NAM.REX * * PROG_NAM
───────────────────────────────────────REXX-r4 4.00 16 Aug 2015 ◄──► subroutine
     REXX's name of system being used: Win32
     how the REXX program was invoked: SUBROUTINE
    name of the REXX program and path: C:\PROG_NAM.REX * * PROG_NAM
─────────────────────────────────────────REXX-r4 4.00 16 Aug 2015 ◄──► function
     REXX's name of system being used: Win32
     how the REXX program was invoked: FUNCTION
    name of the REXX program and path: C:\PROG_NAM.REX * * PROG_NAM

output   when using REGINA REXX with the input of:   command

────────────────────────────────────REXX-Regina_3.9.1(MT) 5.00 5 Apr 2015 ◄──► command
     REXX's name of system being used: WIN32
     how the REXX program was invoked: COMMAND
    name of the REXX program and path: c:\prog_nam.rex
──────────────────────────REXX-Regina_3.9.1(MT) 5.00 5 Apr 2015 ◄──► subroutine
     REXX's name of system being used: WIN32
     how the REXX program was invoked: SUBROUTINE
    name of the REXX program and path: c:\PROG_NAM.rex
────────────────────────────REXX-Regina_3.9.1(MT) 5.00 5 Apr 2015 ◄──► function
     REXX's name of system being used: WIN32
     how the REXX program was invoked: FUNCTION
    name of the REXX program and path: c:\PROG_NAM.rex

output   when using Personal REXX with the input of:   command

────────────────────────────────────REXX/Personal 4.00 21 Mar 1992 ◄──► command
     REXX's name of system being used: PCDOS
     how the REXX program was invoked: COMMAND
    name of the REXX program and path: D:\PROG_NAM.REX
─────────────────────────────────REXX/Personal 4.00 21 Mar 1992 ◄──► subroutine
     REXX's name of system being used: PCDOS
     how the REXX program was invoked: SUBROUTINE
    name of the REXX program and path: D:\PROG_NAM.REX
───────────────────────────────────REXX/Personal 4.00 21 Mar 1992 ◄──► function
     REXX's name of system being used: PCDOS
     how the REXX program was invoked: FUNCTION
    name of the REXX program and path: D:\PROG_NAM.REX

output   when using ROO REXX with the input of:   command

─────────────────────────────────────────REXX-roo 4.00 28 Jan 2007 ◄──► command
     REXX's name of system being used: Win32
     how the REXX program was invoked: COMMAND
    name of the REXX program and path: D:\PROG_NAM.REX * * PROG_NAM
──────────────────────────────────────REXX-roo 4.00 28 Jan 2007 ◄──► subroutine
     REXX's name of system being used: Win32
     how the REXX program was invoked: SUBROUTINE
    name of the REXX program and path: D:\PROG_NAM.REX * * PROG_NAM
────────────────────────────────────────REXX-roo 4.00 28 Jan 2007 ◄──► function
     REXX's name of system being used: Win32
     how the REXX program was invoked: FUNCTION
    name of the REXX program and path: D:\PROG_NAM.REX * * PROG_NAM

output   when using ooRexx with the input of:   command

-----------------------------------REXX-ooRexx_4.1.2(MT) 6.03 28 Aug 2012 ?--?
     REXX's name of system being used: WindowsNT
     how the REXX program was invoked: COMMAND
    name of the REXX program and path: E:\PROG_NAM.REX
-------------------------REXX-ooRexx_4.1.2(MT) 6.03 28 Aug 2012 ?--? subroutine
     REXX's name of system being used: WindowsNT
     how the REXX program was invoked: SUBROUTINE
    name of the REXX program and path: E:\PROG_NAM.REX
---------------------------REXX-ooRexx_4.1.2(MT) 6.03 28 Aug 2012 ?--? function
     REXX's name of system being used: WindowsNT
     how the REXX program was invoked: FUNCTION
    name of the REXX program and path: E:\PROG_NAM.REX                

Output note of ooRexx (which should be shown in the ooRexx language section):   the output from ooRexx (in this Classic REXX section) needs to be corrected and re-done;   the title is different, it is not showing the argument supplied, and it's incorrectly translating the (solid) left and right arrow characters.

Ring

see "Active Source File Name : " + filename() + nl

output

Active Source File Name : tests\filename.ring

Check the main file in the program

if sysargv[2] = filename()
        see "I'm the main program file!" + nl
        # we can run tests here!
else
        see "I'm a sub file in a program" + nl
ok

Ruby

#!/usr/bin/env ruby

puts "Path: #{$PROGRAM_NAME}"  # or puts "Path: #{$0}"
puts "Name: #{File.basename $0}"

For example,

$ ruby script.rb                                                               
Path: script.rb
Name: script.rb
$ ruby ../rc/script.rb
Path: ../rc/script.rb
Name: script.rb
$ ruby -e 'load "script.rb"'
Path: -e
Name: -e

Rust

scriptname.rs:

fn main() {
    println!("Program: {}", std::env::args().next().unwrap());
}

Example:

$ rustc scriptname.rs
$ ./scriptname
Program: ./scriptname

SAC

scriptname.sac:

use StdIO: all;
use Array: all;
use String: { string };
use CommandLine: all;

int main() {
	program = argv(0);
	printf("Program: %s\n", program);
	return(0);
}

Makefile:

all: scriptname

scriptname: scriptname.sac
	sac2c -o scriptname scriptname.sac

clean:
	-rm scriptname
	-rm scriptname.c

Example:

$ make
sac2c -o scriptname scriptname.sac
$ ./scriptname 
Program: ./scriptname

Scala

object ScriptName extends App {
  println(s"Program of instantiated object: ${this.getClass.getName}")
  // Not recommended, due various implementations
  println(s"Program via enviroment:         ${System.getProperty("sun.java.command")}")
}

Scheme

Works with: Chicken Scheme

Getting the program name is tricky. When interpreted, the script name will be printed. When compiled, the executable name will be printed.

#!/bin/sh
#|
exec csi -ss $0 ${1+"$@"}
exit
|#

(use posix)
(require-extension srfi-1) ; lists
(require-extension srfi-13) ; strings

(define (main args)
	(let ((prog (cdr (program))))
		(display (format "Program: ~a\n" prog))
		(exit)))

(define (program)
	(if (string=? (car (argv)) "csi")
		(let ((s-index (list-index (lambda (x) (string-contains x "-s")) (argv))))
			(if (number? s-index)
				(cons 'interpreted (list-ref (argv) (+ 1 s-index)))
				(cons 'unknown "")))
		(cons 'compiled (car (argv)))))

(if (equal? (car (program)) 'compiled)
	(main (cdr (argv))))

Seed7

The function path(PROGRAM) returns the path of the file executed. When the program is interpreted this is the path of the source file. When the program is compiled this is the path of the executable. The functions dir(PROGRAM) and file(PROGRAM) deliver the directory respectivly file name of the program path.

$ include "seed7_05.s7i";

const proc: main is func
  local
    var integer: i is 0;
  begin
    writeln("Program path:      " <& path(PROGRAM));
    writeln("Program directory: " <& dir(PROGRAM));
    writeln("Program file:      " <& file(PROGRAM));
  end func;

Output when the program is interpreted:

Program path:      /home/anyuser/seed7_5/prg/programname.sd7
Program directory: /home/anyuser/seed7_5/prg
Program file:      programname.sd7

Output when the program is compiled:

Program path:      /home/anyuser/seed7_5/prg/programname
Program directory: /home/anyuser/seed7_5/prg
Program file:      programname

Sidef

say __MAIN__;
if (__MAIN__ != __FILE__) {
    say "This file has been included!";
}

Smalltalk

Works with: GNU Smalltalk

Note that this only works when run as "./scriptname.st", because the shebang must force the script name onto ARGV.

"exec" "gst" "-f" "$0" "$0" "$@"
"exit"

| program |

program := Smalltalk getArgv: 1.

Transcript show: 'Program: ', program; cr.
Works with: Smalltalk/X

Works when run in script mode or in a workspace.

| program |

program := Smalltalk commandLine first.
Transcript show: 'Program: ', program; cr.

Standard ML

#!/usr/bin/env sml

let
	val program = CommandLine.name ()
in
	print ("Program: " ^ program ^ "\n")
end;

Tcl

#!/usr/bin/env tclsh

proc main {args} {
    set program $::argv0
    puts "Program: $program"
}
 
if {$::argv0 eq [info script]} {
    main {*}$::argv
}

Transd

#lang transd

MainModule: {
	_start: (λ 
        (textout (get @progArgs 0))
    )
}

TXR

Given this code in program-name.txr, marked executable:

#!/usr/local/bin/txr -B
@(bind my-name @self-path)

If we run it as an executable:

$ ./program-name.txr
my-name="./program-name.txr"

If we pass it as an argument to txr:

$ txr program-name.txr
my-name="program-name.txr"

If we evaluate the same thing on the command line:

$ txr -c '@(bind my-name @self-path)'
my-name="cmdline"

If we pass in the code on standard input:

$ txr -
@(bind my-name @self-path)
my-name="stdin"

UNIX Shell

Works with: Bourne Shell
#!/bin/sh

echo "Program: $0"

Vala

Get name of program and print to console:

public static void main(string[] args){
	string command_name = args[0];
	
	stdout.printf("%s\n", command_name);
}

Output for program named "filename":

./filename

VBA

VBA can retrieve the name of the program hosting the VBA code using the Application object:

Debug.Print Application.Name

This is mostly useful for code that is shared between, say, Microsoft Excel and Microsoft Word, but has different requirements or actions depending on where it's running.

Wscript.Echo "FullName:",Wscript.FullName

vbscript

vbscript provides the Wscript object. Among its properties are the following:

Wscript.Echo "FullName:",Wscript.FullName
Wscript.Echo "Name:",Wscript.Name
Wscript.Echo "Path:",Wscript.Path
Wscript.Echo "ScriptFullName:",Wscript.ScriptFullName
Wscript.Echo "ScriptName:",Wscript.ScriptName
FullName: C:\WINDOWS\System32\CScript.exe
Name: Windows Script Host
Path: C:\WINDOWS\System32
ScriptFullName: D:\Utils\test.vbs
ScriptName: test.vbs

Visual Basic

Visual Basic provides the App object, which has a property called EXEName that contains the program's filename without the extension. (For most uses, this doesn't matter, but for code shared between, for example, a program and a screensaver, it can be important.) So, if a program is called "MyVBapp.exe", retreiving the value of App.EXEName would look like this:

appname = App.EXEName 'appname = "MyVBapp"

Alternately, Visual Basic can make an API call:

Declare Function GetModuleFileName Lib "kernel32" Alias "GetModuleFileNameA" (ByVal hModule As Long, ByVal lpFileName As String, ByVal nSize As Long) As Long
Dim fullpath As String * 260, appname As String, namelen As Long
namelen = GetModuleFileName (0, fullpath, 260)
fullpath = Left$(fullpath, namelen)
If InStr(fullpath, "\") Then
    appname = Mid$(fullpath, InStrRev(fullpath, "\") + 1)
Else
    appname = fullpath
End If

Wren

Assuming we're running a script file named "Program_name.wren":

import "os" for Process

System.print("My name is %(Process.allArguments[1])")
Output:
My name is Program_name.wren

x86 Assembly

Works with: Nasm

Linux

Makefile:

FORMAT=-f elf
RUN=./
BIN=scriptname
OBJ=scriptname.o

all: test

test: $(BIN)
	$(RUN)$(BIN)

$(BIN): $(OBJ)
	ld -o $(BIN) $(OBJ)

$(OBJ): scriptname.asm
	nasm $(FORMAT) -o $(OBJ) scriptname.asm

clean:
	-rm $(BIN)
	-rm $(OBJ)

scriptname.asm:

bits 32

section .data

stdout equ 1

sys_write equ 4
sys_exit equ 1

kernel equ 0x80

program db "Program: ", 0
programlen equ $-program

nl db "", 10, 0
nllen equ $-nl

section .bss

scriptname resd 1
scriptnamelen resd 1

section .text

global _start

strlen:							; eax: a string ending in 0
	push eax						; cache eax

	.strloop:
		mov bl, byte [eax]
		cmp bl, 0
		je .strret						; return len if bl == 0
		inc eax							; else eax++
		jmp .strloop

	.strret:
		pop ebx							; ebx = cached eax
		sub eax, ebx					; eax -= ebx
		ret								; eax = len

_start:
	mov eax, esp
	add eax, 4
	mov eax, [eax]
	mov dword [scriptname], eax

	mov eax, sys_write
	mov ebx, stdout
	mov ecx, program
	mov edx, programlen
	int kernel

	mov dword eax, [scriptname]
	call strlen
	mov dword [scriptnamelen], eax

	mov eax, sys_write
	mov ebx, stdout
	mov dword ecx, [scriptname]
	mov dword edx, [scriptnamelen]
	int kernel

	mov eax, sys_write
	mov ebx, stdout
	mov ecx, nl
	mov edx, nllen
	int kernel

	mov eax, sys_exit
	mov ebx, 0
	int kernel

FreeBSD/Mac OS X

Makefile:

# FreeBSD defaults

FORMAT=-f elf
RUN=./
BIN=scriptname
OBJ=scriptname.o

# Mac OS X
ifeq ($(shell uname -s),Darwin)
	FORMAT=-f macho
	MINV=-macosx_version_min 10.6
endif

all: test

test: $(BIN)
	$(RUN)$(BIN)

$(BIN): $(OBJ)
	ld -o $(BIN) $(MINV) $(OBJ)

$(OBJ): scriptname.asm
	nasm $(FORMAT) -o $(OBJ) scriptname.asm

clean:
	-rm $(BIN)
	-rm $(OBJ)

scriptname.asm:

bits 32

section .data

stdout equ 1

sys_write equ 4
sys_exit equ 1

kernel equ 0x80

program db "Program: ", 0
programlen equ $-program

nl db "", 10, 0
nllen equ $-nl

section .bss

scriptname resd 1
scriptnamelen resd 1

section .text

global start

strlen:							; eax: a string ending in 0
	push eax						; cache eax

	.strloop:
		mov bl, byte [eax]
		cmp bl, 0
		je .strret						; return len if bl == 0
		inc eax							; else eax++
		jmp .strloop

	.strret:
		pop ebx							; ebx = cached eax
		sub eax, ebx					; eax -= ebx
		ret								; eax = len

start:
	mov eax, esp
	add eax, 4
	mov eax, [eax]
	mov dword [scriptname], eax

	push programlen
	push program
	push stdout
	mov eax, sys_write
	sub esp, 4
	int kernel
	add esp, 4 + 4 * 3

	mov dword eax, [scriptname]
	call strlen
	mov dword [scriptnamelen], eax

	push dword [scriptnamelen]
	push dword [scriptname]
	push stdout
	mov eax, sys_write
	sub esp, 4
	int kernel
	add esp, 4 + 4 * 3

	push nllen
	push nl
	push stdout
	mov eax, sys_write
	sub esp, 4
	int kernel
	add esp, 4 + 4 * 3

	push 0
	mov eax, sys_exit
	sub esp, 4
	int kernel

Windows

Makefile:

FORMAT=-f win32
BIN=scriptname.exe
OBJ=scriptname.obj
RUN=

all: test

test: $(BIN)
	$(RUN)$(BIN)

$(BIN): $(OBJ)
	golink /fo $(BIN) $(OBJ) /console kernel32.dll Msvcrt.dll

$(OBJ): scriptname.asm
	nasm $(FORMAT) -o $(OBJ) scriptname.asm

clean:
	-rm $(BIN)
	-rm $(OBJ)

scriptname.asm:

bits 32

section .data

program db "Program: ", 0
programlen equ $-program

nl db "", 13, 10, 0
nllen equ $-nl

stdouthandle equ -11

section .bss

stdout resd 1

charswritten resd 1

env resd 1
argc resd 1
argv resd 255

scriptname resd 1
scriptnamelen resd 1

section .text

global Start
extern GetStdHandle
extern __getmainargs
extern WriteConsoleA
extern ExitProcess

strlen:				; eax: a string ending in 0
	push eax			; cache eax

	.strloop:
		mov bl, byte [eax]
		cmp bl, 0
		je .strret			; return len if bl == 0
		inc eax				; else eax++
		jmp .strloop

	.strret:
		pop ebx				; ebx = cached eax
		sub eax, ebx		; eax -= ebx
		ret					; eax = len

Start:
	push 0
	push env
	push argv
	push argc
	call __getmainargs
	mov eax, [argv]
	mov eax, [eax]
	mov [scriptname], eax
	add esp, 4 * 4

	push stdouthandle
	call GetStdHandle
	mov [stdout], eax
	add esp, 4 * 1

	push 0
	push charswritten
	push programlen
	push program
	push dword [stdout]
	call WriteConsoleA
	add esp, 4 * 5

	mov eax, [scriptname]
	call strlen
	mov [scriptnamelen], eax

	push 0
	push charswritten
	push dword [scriptnamelen]
	push dword [scriptname]
	push dword [stdout]
	call WriteConsoleA
	add esp, 4 * 5

	push 0
	push charswritten
	push nllen
	push nl
	push dword [stdout]
	call WriteConsoleA
	add esp, 4 * 5

	push 0
	call ExitProcess

Yabasic

print peek$("program_name")

s$ = system$("cd")
n = len(s$)
print left$(s$, n - 2), "\\", peek$("program_name")

Zig

const std = @import("std");

const debug = std.debug;
const heap = std.heap;
const process = std.process;

pub fn main() !void {
    var args = process.args();

    const program_name = try args.next(heap.page_allocator) orelse unreachable;
    defer heap.page_allocator.free(program_name);

    debug.warn("{}\n", .{program_name});
}

zkl

C's argv is exposed to the zkl runtime so if file bbb.zkl contains:

#!/Homer/craigd/Bin/zkl
println(System.argv);

Then (on Unix like OSes)

./bbb.zkl
zkl bbb.zkl

both print

L("/home/craigd/Projects/ZKL/Bin/zkl","bbb.zkl")

On Unix, zkl is actually a shell script:

#!/bin/sh
# A bash script to run zkl if you haven't jumped 
#   through all the Unix hoops to put the bits in the "right" places
# You can change zklRoot to your build directory, 
#   change the script name to "zkl" and put it in your bin path.
# You may need to chmod a+x <this script>
if [ -z $zklRoot ]; then
   zklRoot=$HOME/ZKL
   if [ ! -d $zklRoot ]; then
      zklRoot=$HOME/Projects/ZKL
   fi
fi
export zklRoot
#set -o noglob
LD_LIBRARY_PATH=$zklRoot/Lib $zklRoot/Bin/zkl "$@"

On Windows, no launch script (windows knows where the DLLs are) but argv[0] can be messed up.