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

ayush
  • 14,350
  • 11
  • 53
  • 100

4 Answers4

62

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.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • we need to write the extention ?? ".php", what if we don't know the extention ? is there a way ? – Hasni Mar 11 '23 at 13:30
  • @Hasni Try this question: https://stackoverflow.com/questions/125281/how-do-i-remove-the-file-suffix-and-path-portion-from-a-path-string-in-bash – Aaron Digulla Mar 13 '23 at 19:50
27

Use the built in UNIX command:

basename "/var/www/html/test.php"
Hogsmill
  • 1,574
  • 13
  • 21
4

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

Chetan Wadhwa
  • 129
  • 1
  • 14
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
Anjan Biswas
  • 7,746
  • 5
  • 47
  • 77