Intecpsp
Intecpsp

Reputation: 362

How do I put basename into a variable?

#!/bin/bash
file=debian.deb
test=basename $file .deb
DP="blah/blah/$test/$test.php"
read -p "[$DP]: " DPREPLY
DPREPLY=${DPREPLY:-$DP}
echo "Blah is set to $DPREPLY"
echo $DPREPLY>>testfile

So what I'm trying to do is set the variable test from the variable file and use it in the file testfile.

Upvotes: 20

Views: 31482

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 754590

Use the command substitution $(...) mechanism:

test=$(basename "$file" .deb)

You can also use backquotes, but these are not recommended in modern scripts (mainly because they don't nest as well as the $(...) notation).

test=`basename "$file" .deb`

You need to know about backquotes in order to interpret other people's scripts; you shouldn't be using them in your own.

Note the use of quotes around "$file"; this ensures that spaces in filenames are handled correctly.

Upvotes: 43

Related Questions