24

Hello i want a simple shell script that find the name of the file from a given path of the file. like

$path = "/var/www/html/test.php";

then i want to get value "test" in some variable. Also only .php files are present.I am using bash shell. Thanks

4 Answers 4

63

Try:

path="/var/www/html/test.php"
name=$(basename "$path" ".php")
echo "$name"

The quotes are only there to prevent problems when $path contains spaces.

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

2 Comments

we need to write the extention ?? ".php", what if we don't know the extention ? is there a way ?
@Hasni Try this question: stackoverflow.com/questions/125281/…
27

Use the built in UNIX command:

basename "/var/www/html/test.php"

Comments

4

Use the basename() function. It is buily in UNIX function

Comments

0
string="/var/www/html/test.php"

oIFS="$IFS"; IFS='/' 
set -A str $string
IFS="$oIFS"

echo "strings count = ${#str[@]}"
len=${#str[@]}
pos=`expr $len - 1`
echo "file : ${str[$pos]}";

Output-

 strings count = 4
 file : test.php

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.