bash 如何将 basename 放入变量中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9556939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:44:08  来源:igfitidea点击:

How do I put basename into a variable?

filebashvariablesdebian

提问by Intecpsp

#!/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.

所以我想要做的是从变量文件中设置变量 test 并在文件 testfile.txt 中使用它。

回答by Jonathan Leffler

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.

请注意在"$file";周围使用引号 这可确保正确处理文件名中的空格。