jonathan
jonathan

Reputation: 291

bash scripting: how to store the source code file's name in a variable?

I want the name of the file where the code is written

for example if the script is written in a file called "name.sh"

then i want to have a variable for example

var=name.sh

where var will hold the file's name

but suppose that i don't know the name of the file, how can I do it?

Upvotes: 0

Views: 327

Answers (4)

Griffin
Griffin

Reputation: 644

You can use $0 which is equivalent argv[0] in some other programming languages.

#!/bin/bash
echo $0
echo $1

If you run the bash script above with $ sh file.sh one two you would get the following output.

test.sh
one
two

Upvotes: 0

Jonathan M
Jonathan M

Reputation: 17451

Looks like you want either $0 or $_, which contain the name of the current script. See here: http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_03_02.html#sect_03_02_04

Upvotes: 0

shadyabhi
shadyabhi

Reputation: 17234

You can use basename.

basename - strip directory and suffix from filenames

var=$(basename $0)

Upvotes: 1

Sean Bright
Sean Bright

Reputation: 120704

You can just use the bash builtin variable $0 for this.

#!/bin/bash

echo This script file is named `basename $0`

If you want to store it in another variable, you can do:

#!/bin/bash

THESCRIPT=$0

echo This script file is named $THESCRIPT

Upvotes: 0

Related Questions