0

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?

4 Answers 4

1

You can use basename.

basename - strip directory and suffix from filenames

var=$(basename $0)

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.