Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 757
Intecpsp Avatar asked Mar 04 '12 17:03

Intecpsp


People also ask

What is basename in bash?

In Linux, the basename command prints the last element of a file path. This is especially useful in bash scripts where the file name needs to be extracted from a long file line. The “basename” takes a filename and prints the filename's last portion. It can also delete any following suffix if needed.

How do you set variables in bash?

The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.


1 Answers

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.

like image 194
Jonathan Leffler Avatar answered Sep 28 '22 02:09

Jonathan Leffler