Bash 基本名称语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12844631/
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
Bash basename syntax
提问by Unknown
I'm trying to write a script that takes the basename of an argument, then checks if there is an extension in that argument. If there is, it prints the extension.
我正在尝试编写一个脚本,该脚本采用参数的基本名称,然后检查该参数中是否有扩展名。如果有,它会打印扩展名。
Here is my code:
这是我的代码:
file=basename
ext=${file%*}
echo ${file#"$stub"}
echo $basename
I'm echoing the final $basename $1 to check what the output of basename is.
我正在回显最终的 $basename $1 以检查 basename 的输出是什么。
Some tests reveal:
一些测试显示:
testfile.sh one.two
./testfile: line 2: one.two: command not found
one.two
testfile.sh ../tester
./testfile: line 2: ../tester: No such file or directory
../tester
So neither $basename $1 are working. I know it's a syntax error so could someone explain what I'm doing wrong?
所以 $basename $1 都不起作用。我知道这是一个语法错误,所以有人可以解释我做错了什么吗?
EDIT:
编辑:
I've solved my problem now with:
我现在已经解决了我的问题:
file=$(basename "" )
stub=${file%.*}
echo ${file#"$stub"}
Which reduces my argument to a basename, thank you all.
这将我的论点简化为基本名称,谢谢大家。
回答by chepner
First, your syntax is wrong:
首先,你的语法是错误的:
file=$( basename "" )
Second, this is the correct expression to get the file name's (last) extension:
其次,这是获取文件名(最后一个)扩展名的正确表达式:
ext=${file##*.}
回答by Janito Vaqueiro Ferreira Filho
If you want to assign to a variable the output of a command, you must execute it, either with back quotes or using a special parenthesis quoting:
如果要将命令的输出分配给变量,则必须使用反引号或使用特殊括号引用来执行它:
file=`basename ""`
file=$(basename "")
To remove a filename's extension you should do
要删除文件名的扩展名,您应该这样做
ext=${file#*.}
this will get the value of $file
, then remove everything up to the period (that's why it is necessary). If your filename contains periods, then you should use ext=${file##*.}
, where the ##
tells bash to delete the longest string that matches instead of the shortest, so it will delete up to the last period, instead of the first one.
这将获得 的值$file
,然后删除该期间之前的所有内容(这就是必要的原因)。如果您的文件名包含句点,那么您应该使用ext=${file##*.}
,##
告诉 bash 删除匹配的最长字符串而不是最短的字符串,因此它将删除到最后一个句点,而不是第一个。
Your echo $basename $1
is wierd. It is telling bash to print the value of a variable called $basename
and the value of the variable $1
, which is the first argument to the script (or function).
你的echo $basename $1
很奇怪。它告诉 bash 打印被调用的变量的值和变量$basename
的值$1
,这是脚本(或函数)的第一个参数。
If you want to print the command you're trying to execute, do this:
如果要打印要执行的命令,请执行以下操作:
echo basename
If you're trying to print the output of the command, you can do one of:
如果您尝试打印命令的输出,您可以执行以下操作之一:
echo $(basename "")
echo "$file"
basename ""
Hope this helps =)
希望这会有所帮助 =)